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