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