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