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