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