]> git.lizzy.rs Git - rust.git/blob - crates/ra_ide/src/syntax_highlighting.rs
Revert function structs back to using bool to track self param, use first param for...
[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, TypeRef, VariantDef};
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(None);
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     /// Remove the `HighlightRange` of `parent` that's currently covered by `child`.
328     fn intersect_partial(parent: &mut HighlightedRange, child: &HighlightedRange) {
329         assert!(
330             parent.range.start() <= child.range.start()
331                 && parent.range.end() >= child.range.start()
332                 && child.range.end() > parent.range.end()
333         );
334
335         parent.range = TextRange::new(parent.range.start(), child.range.start());
336     }
337
338     /// Similar to `pop`, but can modify arbitrary prior ranges (where `pop`)
339     /// can only modify the last range currently on the stack.
340     /// Can be used to do injections that span multiple ranges, like the
341     /// doctest injection below.
342     /// If `overwrite_parent` is non-optional, the highlighting of the parent range
343     /// is overwritten with the argument.
344     ///
345     /// Note that `pop` can be simulated by `pop_and_inject(false)` but the
346     /// latter is computationally more expensive.
347     fn pop_and_inject(&mut self, overwrite_parent: Option<Highlight>) {
348         let mut children = self.stack.pop().unwrap();
349         let prev = self.stack.last_mut().unwrap();
350         children.sort_by_key(|range| range.range.start());
351         prev.sort_by_key(|range| range.range.start());
352
353         for child in children {
354             if let Some(idx) =
355                 prev.iter().position(|parent| parent.range.contains_range(child.range))
356             {
357                 if let Some(tag) = overwrite_parent {
358                     prev[idx].highlight = tag;
359                 }
360
361                 let cloned = Self::intersect(&mut prev[idx], &child);
362                 let insert_idx = if prev[idx].range.is_empty() {
363                     prev.remove(idx);
364                     idx
365                 } else {
366                     idx + 1
367                 };
368                 prev.insert(insert_idx, child);
369                 if !cloned.range.is_empty() {
370                     prev.insert(insert_idx + 1, cloned);
371                 }
372             } else {
373                 let maybe_idx =
374                     prev.iter().position(|parent| parent.range.contains(child.range.start()));
375                 match (overwrite_parent, maybe_idx) {
376                     (Some(_), Some(idx)) => {
377                         Self::intersect_partial(&mut prev[idx], &child);
378                         let insert_idx = if prev[idx].range.is_empty() {
379                             prev.remove(idx);
380                             idx
381                         } else {
382                             idx + 1
383                         };
384                         prev.insert(insert_idx, child);
385                     }
386                     (_, None) => {
387                         let idx = prev
388                             .binary_search_by_key(&child.range.start(), |range| range.range.start())
389                             .unwrap_or_else(|x| x);
390                         prev.insert(idx, child);
391                     }
392                     _ => {
393                         unreachable!("child range should be completely contained in parent range");
394                     }
395                 }
396             }
397         }
398     }
399
400     fn add(&mut self, range: HighlightedRange) {
401         self.stack
402             .last_mut()
403             .expect("during DFS traversal, the stack must not be empty")
404             .push(range)
405     }
406
407     fn flattened(mut self) -> Vec<HighlightedRange> {
408         assert_eq!(
409             self.stack.len(),
410             1,
411             "after DFS traversal, the stack should only contain a single element"
412         );
413         let mut res = self.stack.pop().unwrap();
414         res.sort_by_key(|range| range.range.start());
415         // Check that ranges are sorted and disjoint
416         assert!(res
417             .iter()
418             .zip(res.iter().skip(1))
419             .all(|(left, right)| left.range.end() <= right.range.start()));
420         res
421     }
422 }
423
424 fn highlight_format_specifier(kind: FormatSpecifier) -> Option<HighlightTag> {
425     Some(match kind {
426         FormatSpecifier::Open
427         | FormatSpecifier::Close
428         | FormatSpecifier::Colon
429         | FormatSpecifier::Fill
430         | FormatSpecifier::Align
431         | FormatSpecifier::Sign
432         | FormatSpecifier::NumberSign
433         | FormatSpecifier::DollarSign
434         | FormatSpecifier::Dot
435         | FormatSpecifier::Asterisk
436         | FormatSpecifier::QuestionMark => HighlightTag::FormatSpecifier,
437         FormatSpecifier::Integer | FormatSpecifier::Zero => HighlightTag::NumericLiteral,
438         FormatSpecifier::Identifier => HighlightTag::Local,
439     })
440 }
441
442 fn macro_call_range(macro_call: &ast::MacroCall) -> Option<TextRange> {
443     let path = macro_call.path()?;
444     let name_ref = path.segment()?.name_ref()?;
445
446     let range_start = name_ref.syntax().text_range().start();
447     let mut range_end = name_ref.syntax().text_range().end();
448     for sibling in path.syntax().siblings_with_tokens(Direction::Next) {
449         match sibling.kind() {
450             T![!] | IDENT => range_end = sibling.text_range().end(),
451             _ => (),
452         }
453     }
454
455     Some(TextRange::new(range_start, range_end))
456 }
457
458 fn is_possibly_unsafe(name_ref: &ast::NameRef) -> bool {
459     name_ref
460         .syntax()
461         .parent()
462         .and_then(|parent| {
463             ast::FieldExpr::cast(parent.clone())
464                 .map(|_| true)
465                 .or_else(|| ast::RecordPatField::cast(parent).map(|_| true))
466         })
467         .unwrap_or(false)
468 }
469
470 fn highlight_element(
471     sema: &Semantics<RootDatabase>,
472     bindings_shadow_count: &mut FxHashMap<Name, u32>,
473     syntactic_name_ref_highlighting: bool,
474     element: SyntaxElement,
475 ) -> Option<(Highlight, Option<u64>)> {
476     let db = sema.db;
477     let mut binding_hash = None;
478     let highlight: Highlight = match element.kind() {
479         FN => {
480             bindings_shadow_count.clear();
481             return None;
482         }
483
484         // Highlight definitions depending on the "type" of the definition.
485         NAME => {
486             let name = element.into_node().and_then(ast::Name::cast).unwrap();
487             let name_kind = classify_name(sema, &name);
488
489             if let Some(NameClass::Definition(Definition::Local(local))) = &name_kind {
490                 if let Some(name) = local.name(db) {
491                     let shadow_count = bindings_shadow_count.entry(name.clone()).or_default();
492                     *shadow_count += 1;
493                     binding_hash = Some(calc_binding_hash(&name, *shadow_count))
494                 }
495             };
496
497             match name_kind {
498                 Some(NameClass::ExternCrate(_)) => HighlightTag::Module.into(),
499                 Some(NameClass::Definition(def)) => {
500                     highlight_name(sema, db, def, None, false) | HighlightModifier::Definition
501                 }
502                 Some(NameClass::ConstReference(def)) => highlight_name(sema, db, def, None, false),
503                 Some(NameClass::FieldShorthand { field, .. }) => {
504                     let mut h = HighlightTag::Field.into();
505                     if let Definition::Field(field) = field {
506                         if let VariantDef::Union(_) = field.parent_def(db) {
507                             h |= HighlightModifier::Unsafe;
508                         }
509                     }
510
511                     h
512                 }
513                 None => highlight_name_by_syntax(name) | HighlightModifier::Definition,
514             }
515         }
516
517         // Highlight references like the definitions they resolve to
518         NAME_REF if element.ancestors().any(|it| it.kind() == ATTR) => {
519             Highlight::from(HighlightTag::Function) | HighlightModifier::Attribute
520         }
521         NAME_REF => {
522             let name_ref = element.into_node().and_then(ast::NameRef::cast).unwrap();
523             let possibly_unsafe = is_possibly_unsafe(&name_ref);
524             match classify_name_ref(sema, &name_ref) {
525                 Some(name_kind) => match name_kind {
526                     NameRefClass::ExternCrate(_) => HighlightTag::Module.into(),
527                     NameRefClass::Definition(def) => {
528                         if let Definition::Local(local) = &def {
529                             if let Some(name) = local.name(db) {
530                                 let shadow_count =
531                                     bindings_shadow_count.entry(name.clone()).or_default();
532                                 binding_hash = Some(calc_binding_hash(&name, *shadow_count))
533                             }
534                         };
535                         highlight_name(sema, db, def, Some(name_ref), possibly_unsafe)
536                     }
537                     NameRefClass::FieldShorthand { .. } => HighlightTag::Field.into(),
538                 },
539                 None if syntactic_name_ref_highlighting => {
540                     highlight_name_ref_by_syntax(name_ref, sema)
541                 }
542                 None => HighlightTag::UnresolvedReference.into(),
543             }
544         }
545
546         // Simple token-based highlighting
547         COMMENT => {
548             let comment = element.into_token().and_then(ast::Comment::cast)?;
549             let h = HighlightTag::Comment;
550             match comment.kind().doc {
551                 Some(_) => h | HighlightModifier::Documentation,
552                 None => h.into(),
553             }
554         }
555         STRING | RAW_STRING | RAW_BYTE_STRING | BYTE_STRING => HighlightTag::StringLiteral.into(),
556         ATTR => HighlightTag::Attribute.into(),
557         INT_NUMBER | FLOAT_NUMBER => HighlightTag::NumericLiteral.into(),
558         BYTE => HighlightTag::ByteLiteral.into(),
559         CHAR => HighlightTag::CharLiteral.into(),
560         QUESTION => Highlight::new(HighlightTag::Operator) | HighlightModifier::ControlFlow,
561         LIFETIME => {
562             let h = Highlight::new(HighlightTag::Lifetime);
563             match element.parent().map(|it| it.kind()) {
564                 Some(LIFETIME_PARAM) | Some(LABEL) => h | HighlightModifier::Definition,
565                 _ => h,
566             }
567         }
568         T![&] => {
569             let ref_expr = element.parent().and_then(ast::RefExpr::cast)?;
570             let expr = ref_expr.expr()?;
571             let field_expr = match expr {
572                 ast::Expr::FieldExpr(fe) => fe,
573                 _ => return None,
574             };
575
576             let expr = field_expr.expr()?;
577             let ty = sema.type_of_expr(&expr)?;
578             if !ty.is_packed(db) {
579                 return None;
580             }
581
582             // FIXME This needs layout computation to be correct. It will highlight
583             // more than it should with the current implementation.
584
585             HighlightTag::Operator | HighlightModifier::Unsafe
586         }
587         p if p.is_punct() => match p {
588             T![::] | T![->] | T![=>] | T![&] | T![..] | T![=] | T![@] => {
589                 HighlightTag::Operator.into()
590             }
591             T![!] if element.parent().and_then(ast::MacroCall::cast).is_some() => {
592                 HighlightTag::Macro.into()
593             }
594             T![*] if element.parent().and_then(ast::PtrType::cast).is_some() => {
595                 HighlightTag::Keyword.into()
596             }
597             T![*] if element.parent().and_then(ast::PrefixExpr::cast).is_some() => {
598                 let prefix_expr = element.parent().and_then(ast::PrefixExpr::cast)?;
599
600                 let expr = prefix_expr.expr()?;
601                 let ty = sema.type_of_expr(&expr)?;
602                 if ty.is_raw_ptr() {
603                     HighlightTag::Operator | HighlightModifier::Unsafe
604                 } else if let Some(ast::PrefixOp::Deref) = prefix_expr.op_kind() {
605                     HighlightTag::Operator.into()
606                 } else {
607                     HighlightTag::Punctuation.into()
608                 }
609             }
610             T![-] if element.parent().and_then(ast::PrefixExpr::cast).is_some() => {
611                 HighlightTag::NumericLiteral.into()
612             }
613             _ if element.parent().and_then(ast::PrefixExpr::cast).is_some() => {
614                 HighlightTag::Operator.into()
615             }
616             _ if element.parent().and_then(ast::BinExpr::cast).is_some() => {
617                 HighlightTag::Operator.into()
618             }
619             _ if element.parent().and_then(ast::RangeExpr::cast).is_some() => {
620                 HighlightTag::Operator.into()
621             }
622             _ if element.parent().and_then(ast::RangePat::cast).is_some() => {
623                 HighlightTag::Operator.into()
624             }
625             _ if element.parent().and_then(ast::RestPat::cast).is_some() => {
626                 HighlightTag::Operator.into()
627             }
628             _ if element.parent().and_then(ast::Attr::cast).is_some() => {
629                 HighlightTag::Attribute.into()
630             }
631             _ => HighlightTag::Punctuation.into(),
632         },
633
634         k if k.is_keyword() => {
635             let h = Highlight::new(HighlightTag::Keyword);
636             match k {
637                 T![break]
638                 | T![continue]
639                 | T![else]
640                 | T![if]
641                 | T![loop]
642                 | T![match]
643                 | T![return]
644                 | T![while]
645                 | T![in] => h | HighlightModifier::ControlFlow,
646                 T![for] if !is_child_of_impl(&element) => h | HighlightModifier::ControlFlow,
647                 T![unsafe] => h | HighlightModifier::Unsafe,
648                 T![true] | T![false] => HighlightTag::BoolLiteral.into(),
649                 T![self] => {
650                     let self_param_is_mut = element
651                         .parent()
652                         .and_then(ast::SelfParam::cast)
653                         .and_then(|p| p.mut_token())
654                         .is_some();
655                     // closure to enforce lazyness
656                     let self_path = || {
657                         sema.resolve_path(&element.parent()?.parent().and_then(ast::Path::cast)?)
658                     };
659                     if self_param_is_mut
660                         || matches!(self_path(),
661                             Some(hir::PathResolution::Local(local))
662                                 if local.is_self(db)
663                                     && (local.is_mut(db) || local.ty(db).is_mutable_reference())
664                         )
665                     {
666                         HighlightTag::SelfKeyword | HighlightModifier::Mutable
667                     } else {
668                         HighlightTag::SelfKeyword.into()
669                     }
670                 }
671                 T![ref] => {
672                     let modifier: Option<HighlightModifier> = (|| {
673                         let bind_pat = element.parent().and_then(ast::BindPat::cast)?;
674                         let parent = bind_pat.syntax().parent()?;
675
676                         let ty = if let Some(pat_list) =
677                             ast::RecordFieldPatList::cast(parent.clone())
678                         {
679                             let record_pat =
680                                 pat_list.syntax().parent().and_then(ast::RecordPat::cast)?;
681                             sema.type_of_pat(&ast::Pat::RecordPat(record_pat))
682                         } else if let Some(let_stmt) = ast::LetStmt::cast(parent.clone()) {
683                             let field_expr =
684                                 if let ast::Expr::FieldExpr(field_expr) = let_stmt.initializer()? {
685                                     field_expr
686                                 } else {
687                                     return None;
688                                 };
689
690                             sema.type_of_expr(&field_expr.expr()?)
691                         } else if let Some(record_field_pat) = ast::RecordFieldPat::cast(parent) {
692                             let record_pat = record_field_pat
693                                 .syntax()
694                                 .parent()
695                                 .and_then(ast::RecordFieldPatList::cast)?
696                                 .syntax()
697                                 .parent()
698                                 .and_then(ast::RecordPat::cast)?;
699                             sema.type_of_pat(&ast::Pat::RecordPat(record_pat))
700                         } else {
701                             None
702                         }?;
703
704                         if !ty.is_packed(db) {
705                             return None;
706                         }
707
708                         Some(HighlightModifier::Unsafe)
709                     })();
710
711                     if let Some(modifier) = modifier {
712                         h | modifier
713                     } else {
714                         h
715                     }
716                 }
717                 _ => h,
718             }
719         }
720
721         _ => return None,
722     };
723
724     return Some((highlight, binding_hash));
725
726     fn calc_binding_hash(name: &Name, shadow_count: u32) -> u64 {
727         fn hash<T: std::hash::Hash + std::fmt::Debug>(x: T) -> u64 {
728             use std::{collections::hash_map::DefaultHasher, hash::Hasher};
729
730             let mut hasher = DefaultHasher::new();
731             x.hash(&mut hasher);
732             hasher.finish()
733         }
734
735         hash((name, shadow_count))
736     }
737 }
738
739 fn is_child_of_impl(element: &SyntaxElement) -> bool {
740     match element.parent() {
741         Some(e) => e.kind() == IMPL,
742         _ => false,
743     }
744 }
745
746 fn is_method_call_unsafe(
747     sema: &Semantics<RootDatabase>,
748     method_call_expr: ast::MethodCallExpr,
749 ) -> Option<()> {
750     let expr = method_call_expr.expr()?;
751     let field_expr =
752         if let ast::Expr::FieldExpr(field_expr) = expr { field_expr } else { return None };
753     let ty = sema.type_of_expr(&field_expr.expr()?)?;
754     if !ty.is_packed(sema.db) {
755         return None;
756     }
757
758     let func = sema.resolve_method_call(&method_call_expr)?;
759     if func.has_self_param(sema.db) {
760         let params = func.params(sema.db);
761         if matches!(params.into_iter().next(), Some(TypeRef::Reference(..))) {
762             Some(())
763         } else {
764             None
765         }
766     } else {
767         None
768     }
769 }
770
771 fn highlight_name(
772     sema: &Semantics<RootDatabase>,
773     db: &RootDatabase,
774     def: Definition,
775     name_ref: Option<ast::NameRef>,
776     possibly_unsafe: bool,
777 ) -> Highlight {
778     match def {
779         Definition::Macro(_) => HighlightTag::Macro,
780         Definition::Field(field) => {
781             let mut h = HighlightTag::Field.into();
782             if possibly_unsafe {
783                 if let VariantDef::Union(_) = field.parent_def(db) {
784                     h |= HighlightModifier::Unsafe;
785                 }
786             }
787
788             return h;
789         }
790         Definition::ModuleDef(def) => match def {
791             hir::ModuleDef::Module(_) => HighlightTag::Module,
792             hir::ModuleDef::Function(func) => {
793                 let mut h = HighlightTag::Function.into();
794                 if func.is_unsafe(db) {
795                     h |= HighlightModifier::Unsafe;
796                 } else {
797                     let is_unsafe = name_ref
798                         .and_then(|name_ref| name_ref.syntax().parent())
799                         .and_then(ast::MethodCallExpr::cast)
800                         .and_then(|method_call_expr| is_method_call_unsafe(sema, method_call_expr));
801                     if is_unsafe.is_some() {
802                         h |= HighlightModifier::Unsafe;
803                     }
804                 }
805                 return h;
806             }
807             hir::ModuleDef::Adt(hir::Adt::Struct(_)) => HighlightTag::Struct,
808             hir::ModuleDef::Adt(hir::Adt::Enum(_)) => HighlightTag::Enum,
809             hir::ModuleDef::Adt(hir::Adt::Union(_)) => HighlightTag::Union,
810             hir::ModuleDef::EnumVariant(_) => HighlightTag::EnumVariant,
811             hir::ModuleDef::Const(_) => HighlightTag::Constant,
812             hir::ModuleDef::Trait(_) => HighlightTag::Trait,
813             hir::ModuleDef::TypeAlias(_) => HighlightTag::TypeAlias,
814             hir::ModuleDef::BuiltinType(_) => HighlightTag::BuiltinType,
815             hir::ModuleDef::Static(s) => {
816                 let mut h = Highlight::new(HighlightTag::Static);
817                 if s.is_mut(db) {
818                     h |= HighlightModifier::Mutable;
819                     h |= HighlightModifier::Unsafe;
820                 }
821                 return h;
822             }
823         },
824         Definition::SelfType(_) => HighlightTag::SelfType,
825         Definition::TypeParam(_) => HighlightTag::TypeParam,
826         Definition::Local(local) => {
827             let tag =
828                 if local.is_param(db) { HighlightTag::ValueParam } else { HighlightTag::Local };
829             let mut h = Highlight::new(tag);
830             if local.is_mut(db) || local.ty(db).is_mutable_reference() {
831                 h |= HighlightModifier::Mutable;
832             }
833             return h;
834         }
835     }
836     .into()
837 }
838
839 fn highlight_name_by_syntax(name: ast::Name) -> Highlight {
840     let default = HighlightTag::UnresolvedReference;
841
842     let parent = match name.syntax().parent() {
843         Some(it) => it,
844         _ => return default.into(),
845     };
846
847     let tag = match parent.kind() {
848         STRUCT => HighlightTag::Struct,
849         ENUM => HighlightTag::Enum,
850         UNION => HighlightTag::Union,
851         TRAIT => HighlightTag::Trait,
852         TYPE_ALIAS => HighlightTag::TypeAlias,
853         TYPE_PARAM => HighlightTag::TypeParam,
854         RECORD_FIELD => HighlightTag::Field,
855         MODULE => HighlightTag::Module,
856         FN => HighlightTag::Function,
857         CONST => HighlightTag::Constant,
858         STATIC => HighlightTag::Static,
859         VARIANT => HighlightTag::EnumVariant,
860         IDENT_PAT => HighlightTag::Local,
861         _ => default,
862     };
863
864     tag.into()
865 }
866
867 fn highlight_name_ref_by_syntax(name: ast::NameRef, sema: &Semantics<RootDatabase>) -> Highlight {
868     let default = HighlightTag::UnresolvedReference;
869
870     let parent = match name.syntax().parent() {
871         Some(it) => it,
872         _ => return default.into(),
873     };
874
875     match parent.kind() {
876         METHOD_CALL_EXPR => {
877             let mut h = Highlight::new(HighlightTag::Function);
878             let is_unsafe = ast::MethodCallExpr::cast(parent)
879                 .and_then(|method_call_expr| is_method_call_unsafe(sema, method_call_expr));
880
881             if is_unsafe.is_some() {
882                 h |= HighlightModifier::Unsafe;
883             }
884
885             h
886         }
887         FIELD_EXPR => {
888             let h = HighlightTag::Field;
889             let is_union = ast::FieldExpr::cast(parent)
890                 .and_then(|field_expr| {
891                     let field = sema.resolve_field(&field_expr)?;
892                     Some(if let VariantDef::Union(_) = field.parent_def(sema.db) {
893                         true
894                     } else {
895                         false
896                     })
897                 })
898                 .unwrap_or(false);
899             if is_union { h | HighlightModifier::Unsafe } else { h.into() }
900         }
901         PATH_SEGMENT => {
902             let path = match parent.parent().and_then(ast::Path::cast) {
903                 Some(it) => it,
904                 _ => return default.into(),
905             };
906             let expr = match path.syntax().parent().and_then(ast::PathExpr::cast) {
907                 Some(it) => it,
908                 _ => {
909                     // within path, decide whether it is module or adt by checking for uppercase name
910                     return if name.text().chars().next().unwrap_or_default().is_uppercase() {
911                         HighlightTag::Struct
912                     } else {
913                         HighlightTag::Module
914                     }
915                     .into();
916                 }
917             };
918             let parent = match expr.syntax().parent() {
919                 Some(it) => it,
920                 None => return default.into(),
921             };
922
923             match parent.kind() {
924                 CALL_EXPR => HighlightTag::Function.into(),
925                 _ => if name.text().chars().next().unwrap_or_default().is_uppercase() {
926                     HighlightTag::Struct.into()
927                 } else {
928                     HighlightTag::Constant
929                 }
930                 .into(),
931             }
932         }
933         _ => default.into(),
934     }
935 }