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