]> git.lizzy.rs Git - rust.git/blob - crates/ide/src/syntax_highlighting/highlight.rs
Merge #8637
[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]
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                 _ => h,
259             }
260         }
261
262         _ => return None,
263     };
264
265     return Some((highlight, binding_hash));
266
267     fn calc_binding_hash(name: &hir::Name, shadow_count: u32) -> u64 {
268         fn hash<T: std::hash::Hash + std::fmt::Debug>(x: T) -> u64 {
269             use std::{collections::hash_map::DefaultHasher, hash::Hasher};
270
271             let mut hasher = DefaultHasher::new();
272             x.hash(&mut hasher);
273             hasher.finish()
274         }
275
276         hash((name, shadow_count))
277     }
278 }
279 fn highlight_def(db: &RootDatabase, def: Definition) -> Highlight {
280     match def {
281         Definition::Macro(_) => HlTag::Symbol(SymbolKind::Macro),
282         Definition::Field(_) => HlTag::Symbol(SymbolKind::Field),
283         Definition::ModuleDef(def) => match def {
284             hir::ModuleDef::Module(_) => HlTag::Symbol(SymbolKind::Module),
285             hir::ModuleDef::Function(func) => {
286                 let mut h = Highlight::new(HlTag::Symbol(SymbolKind::Function));
287                 if let Some(item) = func.as_assoc_item(db) {
288                     h |= HlMod::Associated;
289                     if func.self_param(db).is_none() {
290                         h |= HlMod::Static
291                     }
292
293                     match item.container(db) {
294                         hir::AssocItemContainer::Impl(i) => {
295                             if i.trait_(db).is_some() {
296                                 h |= HlMod::Trait;
297                             }
298                         }
299                         hir::AssocItemContainer::Trait(_t) => {
300                             h |= HlMod::Trait;
301                         }
302                     }
303                 }
304
305                 if func.is_unsafe(db) {
306                     h |= HlMod::Unsafe;
307                 }
308                 return h;
309             }
310             hir::ModuleDef::Adt(hir::Adt::Struct(_)) => HlTag::Symbol(SymbolKind::Struct),
311             hir::ModuleDef::Adt(hir::Adt::Enum(_)) => HlTag::Symbol(SymbolKind::Enum),
312             hir::ModuleDef::Adt(hir::Adt::Union(_)) => HlTag::Symbol(SymbolKind::Union),
313             hir::ModuleDef::Variant(_) => HlTag::Symbol(SymbolKind::Variant),
314             hir::ModuleDef::Const(konst) => {
315                 let mut h = Highlight::new(HlTag::Symbol(SymbolKind::Const));
316                 if let Some(item) = konst.as_assoc_item(db) {
317                     h |= HlMod::Associated;
318                     match item.container(db) {
319                         hir::AssocItemContainer::Impl(i) => {
320                             if i.trait_(db).is_some() {
321                                 h |= HlMod::Trait;
322                             }
323                         }
324                         hir::AssocItemContainer::Trait(_t) => {
325                             h |= HlMod::Trait;
326                         }
327                     }
328                 }
329
330                 return h;
331             }
332             hir::ModuleDef::Trait(_) => HlTag::Symbol(SymbolKind::Trait),
333             hir::ModuleDef::TypeAlias(type_) => {
334                 let mut h = Highlight::new(HlTag::Symbol(SymbolKind::TypeAlias));
335                 if let Some(item) = type_.as_assoc_item(db) {
336                     h |= HlMod::Associated;
337                     match item.container(db) {
338                         hir::AssocItemContainer::Impl(i) => {
339                             if i.trait_(db).is_some() {
340                                 h |= HlMod::Trait;
341                             }
342                         }
343                         hir::AssocItemContainer::Trait(_t) => {
344                             h |= HlMod::Trait;
345                         }
346                     }
347                 }
348                 return h;
349             }
350             hir::ModuleDef::BuiltinType(_) => HlTag::BuiltinType,
351             hir::ModuleDef::Static(s) => {
352                 let mut h = Highlight::new(HlTag::Symbol(SymbolKind::Static));
353                 if s.is_mut(db) {
354                     h |= HlMod::Mutable;
355                     h |= HlMod::Unsafe;
356                 }
357                 return h;
358             }
359         },
360         Definition::SelfType(_) => HlTag::Symbol(SymbolKind::Impl),
361         Definition::GenericParam(it) => match it {
362             hir::GenericParam::TypeParam(_) => HlTag::Symbol(SymbolKind::TypeParam),
363             hir::GenericParam::ConstParam(_) => HlTag::Symbol(SymbolKind::ConstParam),
364             hir::GenericParam::LifetimeParam(_) => HlTag::Symbol(SymbolKind::LifetimeParam),
365         },
366         Definition::Local(local) => {
367             let tag = if local.is_self(db) {
368                 HlTag::Symbol(SymbolKind::SelfParam)
369             } else if local.is_param(db) {
370                 HlTag::Symbol(SymbolKind::ValueParam)
371             } else {
372                 HlTag::Symbol(SymbolKind::Local)
373             };
374             let mut h = Highlight::new(tag);
375             let ty = local.ty(db);
376             if local.is_mut(db) || ty.is_mutable_reference() {
377                 h |= HlMod::Mutable;
378             }
379             if ty.as_callable(db).is_some() || ty.impls_fnonce(db) {
380                 h |= HlMod::Callable;
381             }
382             return h;
383         }
384         Definition::Label(_) => HlTag::Symbol(SymbolKind::Label),
385     }
386     .into()
387 }
388
389 fn highlight_func_by_name_ref(
390     sema: &Semantics<RootDatabase>,
391     name_ref: &ast::NameRef,
392 ) -> Option<Highlight> {
393     let mc = name_ref.syntax().parent().and_then(ast::MethodCallExpr::cast)?;
394     highlight_method_call(sema, &mc)
395 }
396
397 fn highlight_method_call(
398     sema: &Semantics<RootDatabase>,
399     method_call: &ast::MethodCallExpr,
400 ) -> Option<Highlight> {
401     let func = sema.resolve_method_call(&method_call)?;
402     let mut h = SymbolKind::Function.into();
403     h |= HlMod::Associated;
404     if func.is_unsafe(sema.db) || sema.is_unsafe_method_call(&method_call) {
405         h |= HlMod::Unsafe;
406     }
407     if func.as_assoc_item(sema.db).and_then(|it| it.containing_trait(sema.db)).is_some() {
408         h |= HlMod::Trait
409     }
410
411     if let Some(self_param) = func.self_param(sema.db) {
412         match self_param.access(sema.db) {
413             hir::Access::Shared => (),
414             hir::Access::Exclusive => h |= HlMod::Mutable,
415             hir::Access::Owned => {
416                 if let Some(receiver_ty) =
417                     method_call.receiver().and_then(|it| sema.type_of_expr(&it))
418                 {
419                     if !receiver_ty.is_copy(sema.db) {
420                         h |= HlMod::Consuming
421                     }
422                 }
423             }
424         }
425     }
426     Some(h)
427 }
428
429 fn highlight_name_by_syntax(name: ast::Name) -> Highlight {
430     let default = HlTag::UnresolvedReference;
431
432     let parent = match name.syntax().parent() {
433         Some(it) => it,
434         _ => return default.into(),
435     };
436
437     let tag = match parent.kind() {
438         STRUCT => SymbolKind::Struct,
439         ENUM => SymbolKind::Enum,
440         VARIANT => SymbolKind::Variant,
441         UNION => SymbolKind::Union,
442         TRAIT => SymbolKind::Trait,
443         TYPE_ALIAS => SymbolKind::TypeAlias,
444         TYPE_PARAM => SymbolKind::TypeParam,
445         RECORD_FIELD => SymbolKind::Field,
446         MODULE => SymbolKind::Module,
447         FN => SymbolKind::Function,
448         CONST => SymbolKind::Const,
449         STATIC => SymbolKind::Static,
450         IDENT_PAT => SymbolKind::Local,
451         _ => return default.into(),
452     };
453
454     tag.into()
455 }
456
457 fn highlight_name_ref_by_syntax(name: ast::NameRef, sema: &Semantics<RootDatabase>) -> Highlight {
458     let default = HlTag::UnresolvedReference;
459
460     let parent = match name.syntax().parent() {
461         Some(it) => it,
462         _ => return default.into(),
463     };
464
465     match parent.kind() {
466         METHOD_CALL_EXPR => {
467             return ast::MethodCallExpr::cast(parent)
468                 .and_then(|it| highlight_method_call(sema, &it))
469                 .unwrap_or_else(|| SymbolKind::Function.into());
470         }
471         FIELD_EXPR => {
472             let h = HlTag::Symbol(SymbolKind::Field);
473             let is_union = ast::FieldExpr::cast(parent)
474                 .and_then(|field_expr| sema.resolve_field(&field_expr))
475                 .map_or(false, |field| {
476                     matches!(field.parent_def(sema.db), hir::VariantDef::Union(_))
477                 });
478             if is_union {
479                 h | HlMod::Unsafe
480             } else {
481                 h.into()
482             }
483         }
484         PATH_SEGMENT => {
485             let path = match parent.parent().and_then(ast::Path::cast) {
486                 Some(it) => it,
487                 _ => return default.into(),
488             };
489             let expr = match path.syntax().parent().and_then(ast::PathExpr::cast) {
490                 Some(it) => it,
491                 _ => {
492                     // within path, decide whether it is module or adt by checking for uppercase name
493                     return if name.text().chars().next().unwrap_or_default().is_uppercase() {
494                         SymbolKind::Struct
495                     } else {
496                         SymbolKind::Module
497                     }
498                     .into();
499                 }
500             };
501             let parent = match expr.syntax().parent() {
502                 Some(it) => it,
503                 None => return default.into(),
504             };
505
506             match parent.kind() {
507                 CALL_EXPR => SymbolKind::Function.into(),
508                 _ => if name.text().chars().next().unwrap_or_default().is_uppercase() {
509                     SymbolKind::Struct
510                 } else {
511                     SymbolKind::Const
512                 }
513                 .into(),
514             }
515         }
516         _ => default.into(),
517     }
518 }
519
520 fn is_consumed_lvalue(
521     node: NodeOrToken<SyntaxNode, SyntaxToken>,
522     local: &hir::Local,
523     db: &RootDatabase,
524 ) -> bool {
525     // When lvalues are passed as arguments and they're not Copy, then mark them as Consuming.
526     parents_match(node, &[PATH_SEGMENT, PATH, PATH_EXPR, ARG_LIST]) && !local.ty(db).is_copy(db)
527 }
528
529 /// Returns true if the parent nodes of `node` all match the `SyntaxKind`s in `kinds` exactly.
530 fn parents_match(mut node: NodeOrToken<SyntaxNode, SyntaxToken>, mut kinds: &[SyntaxKind]) -> bool {
531     while let (Some(parent), [kind, rest @ ..]) = (&node.parent(), kinds) {
532         if parent.kind() != *kind {
533             return false;
534         }
535
536         // FIXME: Would be nice to get parent out of the match, but binding by-move and by-value
537         // in the same pattern is unstable: rust-lang/rust#68354.
538         node = node.parent().unwrap().into();
539         kinds = rest;
540     }
541
542     // Only true if we matched all expected kinds
543     kinds.len() == 0
544 }
545
546 #[inline]
547 fn parent_matches<N: AstNode>(element: &SyntaxElement) -> bool {
548     element.parent().map_or(false, |it| N::can_cast(it.kind()))
549 }
550
551 fn is_child_of_impl(element: &SyntaxElement) -> bool {
552     match element.parent() {
553         Some(e) => e.kind() == IMPL,
554         _ => false,
555     }
556 }