]> git.lizzy.rs Git - rust.git/blob - src/tools/rust-analyzer/crates/ide/src/syntax_highlighting/highlight.rs
Rollup merge of #101171 - thomcc:fix-winfs-ub, r=ChrisDenton
[rust.git] / src / tools / rust-analyzer / crates / ide / src / syntax_highlighting / highlight.rs
1 //! Computes color for a single element.
2
3 use hir::{AsAssocItem, HasVisibility, Semantics};
4 use ide_db::{
5     defs::{Definition, IdentClass, NameClass, NameRefClass},
6     FxHashMap, RootDatabase, SymbolKind,
7 };
8 use syntax::{
9     ast, match_ast, AstNode, AstToken, NodeOrToken,
10     SyntaxKind::{self, *},
11     SyntaxNode, SyntaxToken, T,
12 };
13
14 use crate::{
15     syntax_highlighting::tags::{HlOperator, HlPunct},
16     Highlight, HlMod, HlTag,
17 };
18
19 pub(super) fn token(sema: &Semantics<'_, RootDatabase>, token: SyntaxToken) -> Option<Highlight> {
20     if let Some(comment) = ast::Comment::cast(token.clone()) {
21         let h = HlTag::Comment;
22         return Some(match comment.kind().doc {
23             Some(_) => h | HlMod::Documentation,
24             None => h.into(),
25         });
26     }
27
28     let highlight: Highlight = match token.kind() {
29         STRING | BYTE_STRING => HlTag::StringLiteral.into(),
30         INT_NUMBER if token.parent_ancestors().nth(1).map(|it| it.kind()) == Some(FIELD_EXPR) => {
31             SymbolKind::Field.into()
32         }
33         INT_NUMBER | FLOAT_NUMBER => HlTag::NumericLiteral.into(),
34         BYTE => HlTag::ByteLiteral.into(),
35         CHAR => HlTag::CharLiteral.into(),
36         IDENT if token.parent().and_then(ast::TokenTree::cast).is_some() => {
37             // from this point on we are inside a token tree, this only happens for identifiers
38             // that were not mapped down into macro invocations
39             HlTag::None.into()
40         }
41         p if p.is_punct() => punctuation(sema, token, p),
42         k if k.is_keyword() => keyword(sema, token, k)?,
43         _ => return None,
44     };
45     Some(highlight)
46 }
47
48 pub(super) fn name_like(
49     sema: &Semantics<'_, RootDatabase>,
50     krate: hir::Crate,
51     bindings_shadow_count: &mut FxHashMap<hir::Name, u32>,
52     syntactic_name_ref_highlighting: bool,
53     name_like: ast::NameLike,
54 ) -> Option<(Highlight, Option<u64>)> {
55     let mut binding_hash = None;
56     let highlight = match name_like {
57         ast::NameLike::NameRef(name_ref) => highlight_name_ref(
58             sema,
59             krate,
60             bindings_shadow_count,
61             &mut binding_hash,
62             syntactic_name_ref_highlighting,
63             name_ref,
64         ),
65         ast::NameLike::Name(name) => {
66             highlight_name(sema, bindings_shadow_count, &mut binding_hash, krate, name)
67         }
68         ast::NameLike::Lifetime(lifetime) => match IdentClass::classify_lifetime(sema, &lifetime) {
69             Some(IdentClass::NameClass(NameClass::Definition(def))) => {
70                 highlight_def(sema, krate, def) | HlMod::Definition
71             }
72             Some(IdentClass::NameRefClass(NameRefClass::Definition(def))) => {
73                 highlight_def(sema, krate, def)
74             }
75             // FIXME: Fallback for 'static and '_, as we do not resolve these yet
76             _ => SymbolKind::LifetimeParam.into(),
77         },
78     };
79     Some((highlight, binding_hash))
80 }
81
82 fn punctuation(
83     sema: &Semantics<'_, RootDatabase>,
84     token: SyntaxToken,
85     kind: SyntaxKind,
86 ) -> Highlight {
87     let parent = token.parent();
88     let parent_kind = parent.as_ref().map_or(EOF, SyntaxNode::kind);
89     match (kind, parent_kind) {
90         (T![?], _) => HlTag::Operator(HlOperator::Other) | HlMod::ControlFlow,
91         (T![&], BIN_EXPR) => HlOperator::Bitwise.into(),
92         (T![&], _) => {
93             let h = HlTag::Operator(HlOperator::Other).into();
94             let is_unsafe = parent
95                 .and_then(ast::RefExpr::cast)
96                 .map(|ref_expr| sema.is_unsafe_ref_expr(&ref_expr));
97             if let Some(true) = is_unsafe {
98                 h | HlMod::Unsafe
99             } else {
100                 h
101             }
102         }
103         (T![::] | T![->] | T![=>] | T![..] | T![=] | T![@] | T![.], _) => HlOperator::Other.into(),
104         (T![!], MACRO_CALL | MACRO_RULES) => HlPunct::MacroBang.into(),
105         (T![!], NEVER_TYPE) => HlTag::BuiltinType.into(),
106         (T![!], PREFIX_EXPR) => HlOperator::Logical.into(),
107         (T![*], PTR_TYPE) => HlTag::Keyword.into(),
108         (T![*], PREFIX_EXPR) => {
109             let is_raw_ptr = (|| {
110                 let prefix_expr = parent.and_then(ast::PrefixExpr::cast)?;
111                 let expr = prefix_expr.expr()?;
112                 sema.type_of_expr(&expr)?.original.is_raw_ptr().then(|| ())
113             })();
114             if let Some(()) = is_raw_ptr {
115                 HlTag::Operator(HlOperator::Other) | HlMod::Unsafe
116             } else {
117                 HlOperator::Other.into()
118             }
119         }
120         (T![-], PREFIX_EXPR) => {
121             let prefix_expr = parent.and_then(ast::PrefixExpr::cast).and_then(|e| e.expr());
122             match prefix_expr {
123                 Some(ast::Expr::Literal(_)) => HlTag::NumericLiteral,
124                 _ => HlTag::Operator(HlOperator::Other),
125             }
126             .into()
127         }
128         (T![+] | T![-] | T![*] | T![/] | T![%], BIN_EXPR) => HlOperator::Arithmetic.into(),
129         (T![+=] | T![-=] | T![*=] | T![/=] | T![%=], BIN_EXPR) => {
130             Highlight::from(HlOperator::Arithmetic) | HlMod::Mutable
131         }
132         (T![|] | T![&] | T![!] | T![^] | T![>>] | T![<<], BIN_EXPR) => HlOperator::Bitwise.into(),
133         (T![|=] | T![&=] | T![^=] | T![>>=] | T![<<=], BIN_EXPR) => {
134             Highlight::from(HlOperator::Bitwise) | HlMod::Mutable
135         }
136         (T![&&] | T![||], BIN_EXPR) => HlOperator::Logical.into(),
137         (T![>] | T![<] | T![==] | T![>=] | T![<=] | T![!=], BIN_EXPR) => {
138             HlOperator::Comparison.into()
139         }
140         (_, PREFIX_EXPR | BIN_EXPR | RANGE_EXPR | RANGE_PAT | REST_PAT) => HlOperator::Other.into(),
141         (_, ATTR) => HlTag::AttributeBracket.into(),
142         (kind, _) => match kind {
143             T!['['] | T![']'] => HlPunct::Bracket,
144             T!['{'] | T!['}'] => HlPunct::Brace,
145             T!['('] | T![')'] => HlPunct::Parenthesis,
146             T![<] | T![>] => HlPunct::Angle,
147             T![,] => HlPunct::Comma,
148             T![:] => HlPunct::Colon,
149             T![;] => HlPunct::Semi,
150             T![.] => HlPunct::Dot,
151             _ => HlPunct::Other,
152         }
153         .into(),
154     }
155 }
156
157 fn keyword(
158     sema: &Semantics<'_, RootDatabase>,
159     token: SyntaxToken,
160     kind: SyntaxKind,
161 ) -> Option<Highlight> {
162     let h = Highlight::new(HlTag::Keyword);
163     let h = match kind {
164         T![await] => h | HlMod::Async | HlMod::ControlFlow,
165         T![async] => h | HlMod::Async,
166         T![break]
167         | T![continue]
168         | T![else]
169         | T![if]
170         | T![in]
171         | T![loop]
172         | T![match]
173         | T![return]
174         | T![while]
175         | T![yield] => h | HlMod::ControlFlow,
176         T![for] if parent_matches::<ast::ForExpr>(&token) => h | HlMod::ControlFlow,
177         T![unsafe] => h | HlMod::Unsafe,
178         T![true] | T![false] => HlTag::BoolLiteral.into(),
179         // crate is handled just as a token if it's in an `extern crate`
180         T![crate] if parent_matches::<ast::ExternCrate>(&token) => h,
181         // self, crate, super and `Self` are handled as either a Name or NameRef already, unless they
182         // are inside unmapped token trees
183         T![self] | T![crate] | T![super] | T![Self] if parent_matches::<ast::NameRef>(&token) => {
184             return None
185         }
186         T![self] if parent_matches::<ast::Name>(&token) => return None,
187         T![ref] => match token.parent().and_then(ast::IdentPat::cast) {
188             Some(ident) if sema.is_unsafe_ident_pat(&ident) => h | HlMod::Unsafe,
189             _ => h,
190         },
191         _ => h,
192     };
193     Some(h)
194 }
195
196 fn highlight_name_ref(
197     sema: &Semantics<'_, RootDatabase>,
198     krate: hir::Crate,
199     bindings_shadow_count: &mut FxHashMap<hir::Name, u32>,
200     binding_hash: &mut Option<u64>,
201     syntactic_name_ref_highlighting: bool,
202     name_ref: ast::NameRef,
203 ) -> Highlight {
204     let db = sema.db;
205     if let Some(res) = highlight_method_call_by_name_ref(sema, krate, &name_ref) {
206         return res;
207     }
208
209     let name_class = match NameRefClass::classify(sema, &name_ref) {
210         Some(name_kind) => name_kind,
211         None if syntactic_name_ref_highlighting => {
212             return highlight_name_ref_by_syntax(name_ref, sema, krate)
213         }
214         // FIXME: This is required for helper attributes used by proc-macros, as those do not map down
215         // to anything when used.
216         // We can fix this for derive attributes since derive helpers are recorded, but not for
217         // general attributes.
218         None if name_ref.syntax().ancestors().any(|it| it.kind() == ATTR) => {
219             return HlTag::Symbol(SymbolKind::Attribute).into();
220         }
221         None => return HlTag::UnresolvedReference.into(),
222     };
223     let mut h = match name_class {
224         NameRefClass::Definition(def) => {
225             if let Definition::Local(local) = &def {
226                 let name = local.name(db);
227                 let shadow_count = bindings_shadow_count.entry(name.clone()).or_default();
228                 *binding_hash = Some(calc_binding_hash(&name, *shadow_count))
229             };
230
231             let mut h = highlight_def(sema, krate, def);
232
233             match def {
234                 Definition::Local(local) if is_consumed_lvalue(name_ref.syntax(), &local, db) => {
235                     h |= HlMod::Consuming;
236                 }
237                 Definition::Trait(trait_) if trait_.is_unsafe(db) => {
238                     if ast::Impl::for_trait_name_ref(&name_ref)
239                         .map_or(false, |impl_| impl_.unsafe_token().is_some())
240                     {
241                         h |= HlMod::Unsafe;
242                     }
243                 }
244                 Definition::Field(field) => {
245                     if let Some(parent) = name_ref.syntax().parent() {
246                         if matches!(parent.kind(), FIELD_EXPR | RECORD_PAT_FIELD) {
247                             if let hir::VariantDef::Union(_) = field.parent_def(db) {
248                                 h |= HlMod::Unsafe;
249                             }
250                         }
251                     }
252                 }
253                 Definition::Macro(_) => {
254                     if let Some(macro_call) =
255                         ide_db::syntax_helpers::node_ext::full_path_of_name_ref(&name_ref)
256                             .and_then(|it| it.syntax().parent().and_then(ast::MacroCall::cast))
257                     {
258                         if sema.is_unsafe_macro_call(&macro_call) {
259                             h |= HlMod::Unsafe;
260                         }
261                     }
262                 }
263                 _ => (),
264             }
265
266             h
267         }
268         NameRefClass::FieldShorthand { .. } => SymbolKind::Field.into(),
269     };
270
271     h.tag = match name_ref.token_kind() {
272         T![Self] => HlTag::Symbol(SymbolKind::SelfType),
273         T![self] => HlTag::Symbol(SymbolKind::SelfParam),
274         T![super] | T![crate] => HlTag::Keyword,
275         _ => h.tag,
276     };
277     h
278 }
279
280 fn highlight_name(
281     sema: &Semantics<'_, RootDatabase>,
282     bindings_shadow_count: &mut FxHashMap<hir::Name, u32>,
283     binding_hash: &mut Option<u64>,
284     krate: hir::Crate,
285     name: ast::Name,
286 ) -> Highlight {
287     let name_kind = NameClass::classify(sema, &name);
288     if let Some(NameClass::Definition(Definition::Local(local))) = &name_kind {
289         let name = local.name(sema.db);
290         let shadow_count = bindings_shadow_count.entry(name.clone()).or_default();
291         *shadow_count += 1;
292         *binding_hash = Some(calc_binding_hash(&name, *shadow_count))
293     };
294     match name_kind {
295         Some(NameClass::Definition(def)) => {
296             let mut h = highlight_def(sema, krate, def) | HlMod::Definition;
297             if let Definition::Trait(trait_) = &def {
298                 if trait_.is_unsafe(sema.db) {
299                     h |= HlMod::Unsafe;
300                 }
301             }
302             h
303         }
304         Some(NameClass::ConstReference(def)) => highlight_def(sema, krate, def),
305         Some(NameClass::PatFieldShorthand { field_ref, .. }) => {
306             let mut h = HlTag::Symbol(SymbolKind::Field).into();
307             if let hir::VariantDef::Union(_) = field_ref.parent_def(sema.db) {
308                 h |= HlMod::Unsafe;
309             }
310             h
311         }
312         None => highlight_name_by_syntax(name) | HlMod::Definition,
313     }
314 }
315
316 fn calc_binding_hash(name: &hir::Name, shadow_count: u32) -> u64 {
317     fn hash<T: std::hash::Hash + std::fmt::Debug>(x: T) -> u64 {
318         use std::{collections::hash_map::DefaultHasher, hash::Hasher};
319
320         let mut hasher = DefaultHasher::new();
321         x.hash(&mut hasher);
322         hasher.finish()
323     }
324
325     hash((name, shadow_count))
326 }
327
328 fn highlight_def(
329     sema: &Semantics<'_, RootDatabase>,
330     krate: hir::Crate,
331     def: Definition,
332 ) -> Highlight {
333     let db = sema.db;
334     let mut h = match def {
335         Definition::Macro(m) => Highlight::new(HlTag::Symbol(m.kind(sema.db).into())),
336         Definition::Field(_) => Highlight::new(HlTag::Symbol(SymbolKind::Field)),
337         Definition::Module(module) => {
338             let mut h = Highlight::new(HlTag::Symbol(SymbolKind::Module));
339             if module.is_crate_root(db) {
340                 h |= HlMod::CrateRoot;
341             }
342             h
343         }
344         Definition::Function(func) => {
345             let mut h = Highlight::new(HlTag::Symbol(SymbolKind::Function));
346             if let Some(item) = func.as_assoc_item(db) {
347                 h |= HlMod::Associated;
348                 match func.self_param(db) {
349                     Some(sp) => match sp.access(db) {
350                         hir::Access::Exclusive => {
351                             h |= HlMod::Mutable;
352                             h |= HlMod::Reference;
353                         }
354                         hir::Access::Shared => h |= HlMod::Reference,
355                         hir::Access::Owned => h |= HlMod::Consuming,
356                     },
357                     None => h |= HlMod::Static,
358                 }
359
360                 match item.container(db) {
361                     hir::AssocItemContainer::Impl(i) => {
362                         if i.trait_(db).is_some() {
363                             h |= HlMod::Trait;
364                         }
365                     }
366                     hir::AssocItemContainer::Trait(_t) => {
367                         h |= HlMod::Trait;
368                     }
369                 }
370             }
371
372             if func.is_unsafe_to_call(db) {
373                 h |= HlMod::Unsafe;
374             }
375             if func.is_async(db) {
376                 h |= HlMod::Async;
377             }
378
379             h
380         }
381         Definition::Adt(adt) => {
382             let h = match adt {
383                 hir::Adt::Struct(_) => HlTag::Symbol(SymbolKind::Struct),
384                 hir::Adt::Enum(_) => HlTag::Symbol(SymbolKind::Enum),
385                 hir::Adt::Union(_) => HlTag::Symbol(SymbolKind::Union),
386             };
387
388             Highlight::new(h)
389         }
390         Definition::Variant(_) => Highlight::new(HlTag::Symbol(SymbolKind::Variant)),
391         Definition::Const(konst) => {
392             let mut h = Highlight::new(HlTag::Symbol(SymbolKind::Const));
393
394             if let Some(item) = konst.as_assoc_item(db) {
395                 h |= HlMod::Associated;
396                 match item.container(db) {
397                     hir::AssocItemContainer::Impl(i) => {
398                         if i.trait_(db).is_some() {
399                             h |= HlMod::Trait;
400                         }
401                     }
402                     hir::AssocItemContainer::Trait(_t) => {
403                         h |= HlMod::Trait;
404                     }
405                 }
406             }
407
408             h
409         }
410         Definition::Trait(_) => Highlight::new(HlTag::Symbol(SymbolKind::Trait)),
411         Definition::TypeAlias(type_) => {
412             let mut h = Highlight::new(HlTag::Symbol(SymbolKind::TypeAlias));
413
414             if let Some(item) = type_.as_assoc_item(db) {
415                 h |= HlMod::Associated;
416                 match item.container(db) {
417                     hir::AssocItemContainer::Impl(i) => {
418                         if i.trait_(db).is_some() {
419                             h |= HlMod::Trait;
420                         }
421                     }
422                     hir::AssocItemContainer::Trait(_t) => {
423                         h |= HlMod::Trait;
424                     }
425                 }
426             }
427
428             h
429         }
430         Definition::BuiltinType(_) => Highlight::new(HlTag::BuiltinType),
431         Definition::Static(s) => {
432             let mut h = Highlight::new(HlTag::Symbol(SymbolKind::Static));
433
434             if s.is_mut(db) {
435                 h |= HlMod::Mutable;
436                 h |= HlMod::Unsafe;
437             }
438
439             h
440         }
441         Definition::SelfType(_) => Highlight::new(HlTag::Symbol(SymbolKind::Impl)),
442         Definition::GenericParam(it) => match it {
443             hir::GenericParam::TypeParam(_) => Highlight::new(HlTag::Symbol(SymbolKind::TypeParam)),
444             hir::GenericParam::ConstParam(_) => {
445                 Highlight::new(HlTag::Symbol(SymbolKind::ConstParam))
446             }
447             hir::GenericParam::LifetimeParam(_) => {
448                 Highlight::new(HlTag::Symbol(SymbolKind::LifetimeParam))
449             }
450         },
451         Definition::Local(local) => {
452             let tag = if local.is_self(db) {
453                 HlTag::Symbol(SymbolKind::SelfParam)
454             } else if local.is_param(db) {
455                 HlTag::Symbol(SymbolKind::ValueParam)
456             } else {
457                 HlTag::Symbol(SymbolKind::Local)
458             };
459             let mut h = Highlight::new(tag);
460             let ty = local.ty(db);
461             if local.is_mut(db) || ty.is_mutable_reference() {
462                 h |= HlMod::Mutable;
463             }
464             if local.is_ref(db) || ty.is_reference() {
465                 h |= HlMod::Reference;
466             }
467             if ty.as_callable(db).is_some() || ty.impls_fnonce(db) {
468                 h |= HlMod::Callable;
469             }
470             h
471         }
472         Definition::Label(_) => Highlight::new(HlTag::Symbol(SymbolKind::Label)),
473         Definition::BuiltinAttr(_) => Highlight::new(HlTag::Symbol(SymbolKind::BuiltinAttr)),
474         Definition::ToolModule(_) => Highlight::new(HlTag::Symbol(SymbolKind::ToolModule)),
475         Definition::DeriveHelper(_) => Highlight::new(HlTag::Symbol(SymbolKind::DeriveHelper)),
476     };
477
478     let def_crate = def.krate(db);
479     let is_from_other_crate = def_crate != Some(krate);
480     let is_from_builtin_crate = def_crate.map_or(false, |def_crate| def_crate.is_builtin(db));
481     let is_builtin_type = matches!(def, Definition::BuiltinType(_));
482     let is_public = def.visibility(db) == Some(hir::Visibility::Public);
483
484     match (is_from_other_crate, is_builtin_type, is_public) {
485         (true, false, _) => h |= HlMod::Library,
486         (false, _, true) => h |= HlMod::Public,
487         _ => {}
488     }
489
490     if is_from_builtin_crate {
491         h |= HlMod::DefaultLibrary;
492     }
493
494     h
495 }
496
497 fn highlight_method_call_by_name_ref(
498     sema: &Semantics<'_, RootDatabase>,
499     krate: hir::Crate,
500     name_ref: &ast::NameRef,
501 ) -> Option<Highlight> {
502     let mc = name_ref.syntax().parent().and_then(ast::MethodCallExpr::cast)?;
503     highlight_method_call(sema, krate, &mc)
504 }
505
506 fn highlight_method_call(
507     sema: &Semantics<'_, RootDatabase>,
508     krate: hir::Crate,
509     method_call: &ast::MethodCallExpr,
510 ) -> Option<Highlight> {
511     let func = sema.resolve_method_call(method_call)?;
512
513     let mut h = SymbolKind::Function.into();
514     h |= HlMod::Associated;
515
516     if func.is_unsafe_to_call(sema.db) || sema.is_unsafe_method_call(method_call) {
517         h |= HlMod::Unsafe;
518     }
519     if func.is_async(sema.db) {
520         h |= HlMod::Async;
521     }
522     if func
523         .as_assoc_item(sema.db)
524         .and_then(|it| it.containing_trait_or_trait_impl(sema.db))
525         .is_some()
526     {
527         h |= HlMod::Trait;
528     }
529
530     let def_crate = func.module(sema.db).krate();
531     let is_from_other_crate = def_crate != krate;
532     let is_from_builtin_crate = def_crate.is_builtin(sema.db);
533     let is_public = func.visibility(sema.db) == hir::Visibility::Public;
534
535     if is_from_other_crate {
536         h |= HlMod::Library;
537     } else if is_public {
538         h |= HlMod::Public;
539     }
540
541     if is_from_builtin_crate {
542         h |= HlMod::DefaultLibrary;
543     }
544
545     if let Some(self_param) = func.self_param(sema.db) {
546         match self_param.access(sema.db) {
547             hir::Access::Shared => h |= HlMod::Reference,
548             hir::Access::Exclusive => {
549                 h |= HlMod::Mutable;
550                 h |= HlMod::Reference;
551             }
552             hir::Access::Owned => {
553                 if let Some(receiver_ty) =
554                     method_call.receiver().and_then(|it| sema.type_of_expr(&it))
555                 {
556                     if !receiver_ty.adjusted().is_copy(sema.db) {
557                         h |= HlMod::Consuming
558                     }
559                 }
560             }
561         }
562     }
563     Some(h)
564 }
565
566 fn highlight_name_by_syntax(name: ast::Name) -> Highlight {
567     let default = HlTag::UnresolvedReference;
568
569     let parent = match name.syntax().parent() {
570         Some(it) => it,
571         _ => return default.into(),
572     };
573
574     let tag = match parent.kind() {
575         STRUCT => SymbolKind::Struct,
576         ENUM => SymbolKind::Enum,
577         VARIANT => SymbolKind::Variant,
578         UNION => SymbolKind::Union,
579         TRAIT => SymbolKind::Trait,
580         TYPE_ALIAS => SymbolKind::TypeAlias,
581         TYPE_PARAM => SymbolKind::TypeParam,
582         RECORD_FIELD => SymbolKind::Field,
583         MODULE => SymbolKind::Module,
584         FN => SymbolKind::Function,
585         CONST => SymbolKind::Const,
586         STATIC => SymbolKind::Static,
587         IDENT_PAT => SymbolKind::Local,
588         _ => return default.into(),
589     };
590
591     tag.into()
592 }
593
594 fn highlight_name_ref_by_syntax(
595     name: ast::NameRef,
596     sema: &Semantics<'_, RootDatabase>,
597     krate: hir::Crate,
598 ) -> Highlight {
599     let default = HlTag::UnresolvedReference;
600
601     let parent = match name.syntax().parent() {
602         Some(it) => it,
603         _ => return default.into(),
604     };
605
606     match parent.kind() {
607         METHOD_CALL_EXPR => ast::MethodCallExpr::cast(parent)
608             .and_then(|it| highlight_method_call(sema, krate, &it))
609             .unwrap_or_else(|| SymbolKind::Function.into()),
610         FIELD_EXPR => {
611             let h = HlTag::Symbol(SymbolKind::Field);
612             let is_union = ast::FieldExpr::cast(parent)
613                 .and_then(|field_expr| sema.resolve_field(&field_expr))
614                 .map_or(false, |field| {
615                     matches!(field.parent_def(sema.db), hir::VariantDef::Union(_))
616                 });
617             if is_union {
618                 h | HlMod::Unsafe
619             } else {
620                 h.into()
621             }
622         }
623         PATH_SEGMENT => {
624             let name_based_fallback = || {
625                 if name.text().chars().next().unwrap_or_default().is_uppercase() {
626                     SymbolKind::Struct.into()
627                 } else {
628                     SymbolKind::Module.into()
629                 }
630             };
631             let path = match parent.parent().and_then(ast::Path::cast) {
632                 Some(it) => it,
633                 _ => return name_based_fallback(),
634             };
635             let expr = match path.syntax().parent() {
636                 Some(parent) => match_ast! {
637                     match parent {
638                         ast::PathExpr(path) => path,
639                         ast::MacroCall(_) => return SymbolKind::Macro.into(),
640                         _ => return name_based_fallback(),
641                     }
642                 },
643                 // within path, decide whether it is module or adt by checking for uppercase name
644                 None => return name_based_fallback(),
645             };
646             let parent = match expr.syntax().parent() {
647                 Some(it) => it,
648                 None => return default.into(),
649             };
650
651             match parent.kind() {
652                 CALL_EXPR => SymbolKind::Function.into(),
653                 _ => if name.text().chars().next().unwrap_or_default().is_uppercase() {
654                     SymbolKind::Struct
655                 } else {
656                     SymbolKind::Const
657                 }
658                 .into(),
659             }
660         }
661         _ => default.into(),
662     }
663 }
664
665 fn is_consumed_lvalue(node: &SyntaxNode, local: &hir::Local, db: &RootDatabase) -> bool {
666     // When lvalues are passed as arguments and they're not Copy, then mark them as Consuming.
667     parents_match(node.clone().into(), &[PATH_SEGMENT, PATH, PATH_EXPR, ARG_LIST])
668         && !local.ty(db).is_copy(db)
669 }
670
671 /// Returns true if the parent nodes of `node` all match the `SyntaxKind`s in `kinds` exactly.
672 fn parents_match(mut node: NodeOrToken<SyntaxNode, SyntaxToken>, mut kinds: &[SyntaxKind]) -> bool {
673     while let (Some(parent), [kind, rest @ ..]) = (&node.parent(), kinds) {
674         if parent.kind() != *kind {
675             return false;
676         }
677
678         // FIXME: Would be nice to get parent out of the match, but binding by-move and by-value
679         // in the same pattern is unstable: rust-lang/rust#68354.
680         node = node.parent().unwrap().into();
681         kinds = rest;
682     }
683
684     // Only true if we matched all expected kinds
685     kinds.is_empty()
686 }
687
688 fn parent_matches<N: AstNode>(token: &SyntaxToken) -> bool {
689     token.parent().map_or(false, |it| N::can_cast(it.kind()))
690 }