1 //! Computes color for a single element.
3 use hir::{AsAssocItem, HasVisibility, Semantics};
5 defs::{Definition, NameClass, NameRefClass},
6 RootDatabase, SymbolKind,
8 use rustc_hash::FxHashMap;
10 ast, AstNode, AstToken, NodeOrToken, SyntaxElement,
11 SyntaxKind::{self, *},
12 SyntaxNode, SyntaxToken, T,
16 syntax_highlighting::tags::{HlOperator, HlPunct},
17 Highlight, HlMod, HlTag,
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>)> {
28 let mut binding_hash = None;
29 let highlight: Highlight = match element.kind() {
31 bindings_shadow_count.clear();
35 // Highlight definitions depending on the "type" of the definition.
37 let name = element.into_node().and_then(ast::Name::cast).unwrap();
38 let name_kind = NameClass::classify(sema, &name);
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();
44 binding_hash = Some(calc_binding_hash(&name, *shadow_count))
49 Some(NameClass::ExternCrate(_)) => SymbolKind::Module.into(),
50 Some(NameClass::Definition(def)) => {
51 let mut h = highlight_def(db, krate, def) | HlMod::Definition;
52 if let Definition::ModuleDef(hir::ModuleDef::Trait(trait_)) = &def {
53 if trait_.is_unsafe(db) {
59 Some(NameClass::ConstReference(def)) => highlight_def(db, krate, def),
60 Some(NameClass::PatFieldShorthand { field_ref, .. }) => {
61 let mut h = HlTag::Symbol(SymbolKind::Field).into();
62 if let Definition::Field(field) = field_ref {
63 if let hir::VariantDef::Union(_) = field.parent_def(db) {
69 None => highlight_name_by_syntax(name) | HlMod::Definition,
72 // Highlight references like the definitions they resolve to
73 NAME_REF if element.ancestors().any(|it| it.kind() == ATTR) => {
74 // FIXME: We highlight paths in attributes slightly differently to work around this module
75 // currently not knowing about tool attributes and rustc builtin attributes as
76 // we do not want to resolve those to functions that may be defined in scope.
77 let name_ref = element.into_node().and_then(ast::NameRef::cast).unwrap();
78 match NameRefClass::classify(sema, &name_ref) {
79 Some(name_class) => match name_class {
80 NameRefClass::Definition(Definition::ModuleDef(hir::ModuleDef::Module(_)))
84 .find_map(ast::Path::cast)
85 .map_or(false, |it| it.parent_path().is_some()) =>
87 HlTag::Symbol(SymbolKind::Module)
89 NameRefClass::Definition(Definition::Macro(m))
90 if m.kind() == hir::MacroKind::Attr =>
92 HlTag::Symbol(SymbolKind::Macro)
94 _ => HlTag::BuiltinAttr,
96 None => HlTag::BuiltinAttr,
101 let name_ref = element.into_node().and_then(ast::NameRef::cast).unwrap();
102 highlight_method_call_by_name_ref(sema, krate, &name_ref).unwrap_or_else(|| {
103 let name_class = match NameRefClass::classify(sema, &name_ref) {
104 Some(name_kind) => name_kind,
106 return if syntactic_name_ref_highlighting {
107 highlight_name_ref_by_syntax(name_ref, sema, krate)
109 HlTag::UnresolvedReference.into()
113 let h = match name_class {
114 NameRefClass::ExternCrate(_) => SymbolKind::Module.into(),
115 NameRefClass::Definition(def) => {
116 if let Definition::Local(local) = &def {
117 if let Some(name) = local.name(db) {
119 bindings_shadow_count.entry(name.clone()).or_default();
120 binding_hash = Some(calc_binding_hash(&name, *shadow_count))
124 let mut h = highlight_def(db, krate, def);
127 Definition::Local(local)
128 if is_consumed_lvalue(name_ref.syntax(), &local, db) =>
130 h |= HlMod::Consuming;
132 Definition::ModuleDef(hir::ModuleDef::Trait(trait_))
133 if trait_.is_unsafe(db) =>
135 if ast::Impl::for_trait_name_ref(&name_ref).is_some() {
139 Definition::Field(field) => {
140 if let Some(parent) = name_ref.syntax().parent() {
141 if matches!(parent.kind(), FIELD_EXPR | RECORD_PAT_FIELD) {
142 if let hir::VariantDef::Union(_) = field.parent_def(db) {
153 NameRefClass::FieldShorthand { .. } => SymbolKind::Field.into(),
155 if h.tag == HlTag::Symbol(SymbolKind::Module) && name_ref.self_token().is_some() {
156 SymbolKind::SelfParam.into()
163 // Simple token-based highlighting
165 let comment = element.into_token().and_then(ast::Comment::cast)?;
166 let h = HlTag::Comment;
167 match comment.kind().doc {
168 Some(_) => h | HlMod::Documentation,
172 STRING | BYTE_STRING => HlTag::StringLiteral.into(),
173 ATTR => HlTag::Attribute.into(),
174 INT_NUMBER if element.ancestors().nth(1).map_or(false, |it| it.kind() == FIELD_EXPR) => {
175 SymbolKind::Field.into()
177 INT_NUMBER | FLOAT_NUMBER => HlTag::NumericLiteral.into(),
178 BYTE => HlTag::ByteLiteral.into(),
179 CHAR => HlTag::CharLiteral.into(),
180 QUESTION => HlTag::Operator(HlOperator::Other) | HlMod::ControlFlow,
182 let lifetime = element.into_node().and_then(ast::Lifetime::cast).unwrap();
184 match NameClass::classify_lifetime(sema, &lifetime) {
185 Some(NameClass::Definition(def)) => {
186 highlight_def(db, krate, def) | HlMod::Definition
188 None => match NameRefClass::classify_lifetime(sema, &lifetime) {
189 Some(NameRefClass::Definition(def)) => highlight_def(db, krate, def),
190 _ => SymbolKind::LifetimeParam.into(),
192 _ => Highlight::from(SymbolKind::LifetimeParam) | HlMod::Definition,
195 IDENT if parent_matches::<ast::TokenTree>(&element) => HlTag::None.into(),
196 p if p.is_punct() => match p {
197 T![&] if parent_matches::<ast::BinExpr>(&element) => HlOperator::Bitwise.into(),
199 let h = HlTag::Operator(HlOperator::Other).into();
200 let is_unsafe = element
202 .and_then(ast::RefExpr::cast)
203 .map_or(false, |ref_expr| sema.is_unsafe_ref_expr(&ref_expr));
210 T![::] | T![->] | T![=>] | T![..] | T![=] | T![@] | T![.] => HlOperator::Other.into(),
211 T![!] if parent_matches::<ast::MacroCall>(&element) => SymbolKind::Macro.into(),
212 T![!] if parent_matches::<ast::NeverType>(&element) => HlTag::BuiltinType.into(),
213 T![!] if parent_matches::<ast::PrefixExpr>(&element) => HlOperator::Logical.into(),
214 T![*] if parent_matches::<ast::PtrType>(&element) => HlTag::Keyword.into(),
215 T![*] if parent_matches::<ast::PrefixExpr>(&element) => {
216 let prefix_expr = element.parent().and_then(ast::PrefixExpr::cast)?;
218 let expr = prefix_expr.expr()?;
219 let ty = sema.type_of_expr(&expr)?;
221 HlTag::Operator(HlOperator::Other) | HlMod::Unsafe
222 } else if let Some(ast::PrefixOp::Deref) = prefix_expr.op_kind() {
223 HlOperator::Other.into()
225 HlPunct::Other.into()
228 T![-] if parent_matches::<ast::PrefixExpr>(&element) => {
229 let prefix_expr = element.parent().and_then(ast::PrefixExpr::cast)?;
231 let expr = prefix_expr.expr()?;
233 ast::Expr::Literal(_) => HlTag::NumericLiteral,
234 _ => HlTag::Operator(HlOperator::Other),
238 _ if parent_matches::<ast::PrefixExpr>(&element) => HlOperator::Other.into(),
239 T![+] | T![-] | T![*] | T![/] | T![+=] | T![-=] | T![*=] | T![/=]
240 if parent_matches::<ast::BinExpr>(&element) =>
242 HlOperator::Arithmetic.into()
244 T![|] | T![&] | T![!] | T![^] | T![|=] | T![&=] | T![^=]
245 if parent_matches::<ast::BinExpr>(&element) =>
247 HlOperator::Bitwise.into()
249 T![&&] | T![||] if parent_matches::<ast::BinExpr>(&element) => {
250 HlOperator::Logical.into()
252 T![>] | T![<] | T![==] | T![>=] | T![<=] | T![!=]
253 if parent_matches::<ast::BinExpr>(&element) =>
255 HlOperator::Comparison.into()
257 _ if parent_matches::<ast::BinExpr>(&element) => HlOperator::Other.into(),
258 _ if parent_matches::<ast::RangeExpr>(&element) => HlOperator::Other.into(),
259 _ if parent_matches::<ast::RangePat>(&element) => HlOperator::Other.into(),
260 _ if parent_matches::<ast::RestPat>(&element) => HlOperator::Other.into(),
261 _ if parent_matches::<ast::Attr>(&element) => HlTag::Attribute.into(),
263 T!['['] | T![']'] => HlPunct::Bracket,
264 T!['{'] | T!['}'] => HlPunct::Brace,
265 T!['('] | T![')'] => HlPunct::Parenthesis,
266 T![<] | T![>] => HlPunct::Angle,
267 T![,] => HlPunct::Comma,
268 T![:] => HlPunct::Colon,
269 T![;] => HlPunct::Semi,
270 T![.] => HlPunct::Dot,
276 k if k.is_keyword() => {
277 let h = Highlight::new(HlTag::Keyword);
279 T![await] => h | HlMod::Async | HlMod::ControlFlow,
289 | T![yield] => h | HlMod::ControlFlow,
290 T![for] if !is_child_of_impl(&element) => h | HlMod::ControlFlow,
291 T![unsafe] => h | HlMod::Unsafe,
292 T![true] | T![false] => HlTag::BoolLiteral.into(),
293 // self is handled as either a Name or NameRef already
294 T![self] => return None,
297 .and_then(ast::IdentPat::cast)
298 .and_then(|ident_pat| {
299 if sema.is_unsafe_ident_pat(&ident_pat) {
305 .map(|modifier| h | modifier)
307 T![async] => h | HlMod::Async,
315 return Some((highlight, binding_hash));
317 fn calc_binding_hash(name: &hir::Name, shadow_count: u32) -> u64 {
318 fn hash<T: std::hash::Hash + std::fmt::Debug>(x: T) -> u64 {
319 use std::{collections::hash_map::DefaultHasher, hash::Hasher};
321 let mut hasher = DefaultHasher::new();
326 hash((name, shadow_count))
329 fn highlight_def(db: &RootDatabase, krate: Option<hir::Crate>, def: Definition) -> Highlight {
330 let mut h = match def {
331 Definition::Macro(_) => Highlight::new(HlTag::Symbol(SymbolKind::Macro)),
332 Definition::Field(_) => Highlight::new(HlTag::Symbol(SymbolKind::Field)),
333 Definition::ModuleDef(def) => match def {
334 hir::ModuleDef::Module(_) => Highlight::new(HlTag::Symbol(SymbolKind::Module)),
335 hir::ModuleDef::Function(func) => {
336 let mut h = Highlight::new(HlTag::Symbol(SymbolKind::Function));
337 if let Some(item) = func.as_assoc_item(db) {
338 h |= HlMod::Associated;
339 match func.self_param(db) {
341 if let hir::Access::Exclusive = sp.access(db) {
345 None => h |= HlMod::Static,
348 match item.container(db) {
349 hir::AssocItemContainer::Impl(i) => {
350 if i.trait_(db).is_some() {
354 hir::AssocItemContainer::Trait(_t) => {
360 if func.is_unsafe(db) {
363 if func.is_async(db) {
369 hir::ModuleDef::Adt(adt) => {
371 hir::Adt::Struct(_) => HlTag::Symbol(SymbolKind::Struct),
372 hir::Adt::Enum(_) => HlTag::Symbol(SymbolKind::Enum),
373 hir::Adt::Union(_) => HlTag::Symbol(SymbolKind::Union),
378 hir::ModuleDef::Variant(_) => Highlight::new(HlTag::Symbol(SymbolKind::Variant)),
379 hir::ModuleDef::Const(konst) => {
380 let mut h = Highlight::new(HlTag::Symbol(SymbolKind::Const));
382 if let Some(item) = konst.as_assoc_item(db) {
383 h |= HlMod::Associated;
384 match item.container(db) {
385 hir::AssocItemContainer::Impl(i) => {
386 if i.trait_(db).is_some() {
390 hir::AssocItemContainer::Trait(_t) => {
398 hir::ModuleDef::Trait(_) => Highlight::new(HlTag::Symbol(SymbolKind::Trait)),
399 hir::ModuleDef::TypeAlias(type_) => {
400 let mut h = Highlight::new(HlTag::Symbol(SymbolKind::TypeAlias));
402 if let Some(item) = type_.as_assoc_item(db) {
403 h |= HlMod::Associated;
404 match item.container(db) {
405 hir::AssocItemContainer::Impl(i) => {
406 if i.trait_(db).is_some() {
410 hir::AssocItemContainer::Trait(_t) => {
418 hir::ModuleDef::BuiltinType(_) => Highlight::new(HlTag::BuiltinType),
419 hir::ModuleDef::Static(s) => {
420 let mut h = Highlight::new(HlTag::Symbol(SymbolKind::Static));
430 Definition::SelfType(_) => Highlight::new(HlTag::Symbol(SymbolKind::Impl)),
431 Definition::GenericParam(it) => match it {
432 hir::GenericParam::TypeParam(_) => Highlight::new(HlTag::Symbol(SymbolKind::TypeParam)),
433 hir::GenericParam::ConstParam(_) => {
434 Highlight::new(HlTag::Symbol(SymbolKind::ConstParam))
436 hir::GenericParam::LifetimeParam(_) => {
437 Highlight::new(HlTag::Symbol(SymbolKind::LifetimeParam))
440 Definition::Local(local) => {
441 let tag = if local.is_self(db) {
442 HlTag::Symbol(SymbolKind::SelfParam)
443 } else if local.is_param(db) {
444 HlTag::Symbol(SymbolKind::ValueParam)
446 HlTag::Symbol(SymbolKind::Local)
448 let mut h = Highlight::new(tag);
449 let ty = local.ty(db);
450 if local.is_mut(db) || ty.is_mutable_reference() {
453 if ty.as_callable(db).is_some() || ty.impls_fnonce(db) {
454 h |= HlMod::Callable;
458 Definition::Label(_) => Highlight::new(HlTag::Symbol(SymbolKind::Label)),
461 let is_from_other_crate = def.module(db).map(hir::Module::krate) != krate;
462 let is_builtin_type = matches!(def, Definition::ModuleDef(hir::ModuleDef::BuiltinType(_)));
463 let is_public = def.visibility(db) == Some(hir::Visibility::Public);
465 match (is_from_other_crate, is_builtin_type, is_public) {
466 (true, false, _) => h |= HlMod::Library,
467 (false, _, true) => h |= HlMod::Public,
474 fn highlight_method_call_by_name_ref(
475 sema: &Semantics<RootDatabase>,
476 krate: Option<hir::Crate>,
477 name_ref: &ast::NameRef,
478 ) -> Option<Highlight> {
479 let mc = name_ref.syntax().parent().and_then(ast::MethodCallExpr::cast)?;
480 highlight_method_call(sema, krate, &mc)
483 fn highlight_method_call(
484 sema: &Semantics<RootDatabase>,
485 krate: Option<hir::Crate>,
486 method_call: &ast::MethodCallExpr,
487 ) -> Option<Highlight> {
488 let func = sema.resolve_method_call(method_call)?;
490 let mut h = SymbolKind::Function.into();
491 h |= HlMod::Associated;
493 if func.is_unsafe(sema.db) || sema.is_unsafe_method_call(method_call) {
496 if func.is_async(sema.db) {
499 if func.as_assoc_item(sema.db).and_then(|it| it.containing_trait(sema.db)).is_some() {
503 let is_from_other_crate = Some(func.module(sema.db).krate()) != krate;
504 let is_public = func.visibility(sema.db) == hir::Visibility::Public;
506 if is_from_other_crate {
508 } else if is_public {
512 if let Some(self_param) = func.self_param(sema.db) {
513 match self_param.access(sema.db) {
514 hir::Access::Shared => (),
515 hir::Access::Exclusive => h |= HlMod::Mutable,
516 hir::Access::Owned => {
517 if let Some(receiver_ty) =
518 method_call.receiver().and_then(|it| sema.type_of_expr(&it))
520 if !receiver_ty.is_copy(sema.db) {
521 h |= HlMod::Consuming
530 fn highlight_name_by_syntax(name: ast::Name) -> Highlight {
531 let default = HlTag::UnresolvedReference;
533 let parent = match name.syntax().parent() {
535 _ => return default.into(),
538 let tag = match parent.kind() {
539 STRUCT => SymbolKind::Struct,
540 ENUM => SymbolKind::Enum,
541 VARIANT => SymbolKind::Variant,
542 UNION => SymbolKind::Union,
543 TRAIT => SymbolKind::Trait,
544 TYPE_ALIAS => SymbolKind::TypeAlias,
545 TYPE_PARAM => SymbolKind::TypeParam,
546 RECORD_FIELD => SymbolKind::Field,
547 MODULE => SymbolKind::Module,
548 FN => SymbolKind::Function,
549 CONST => SymbolKind::Const,
550 STATIC => SymbolKind::Static,
551 IDENT_PAT => SymbolKind::Local,
552 _ => return default.into(),
558 fn highlight_name_ref_by_syntax(
560 sema: &Semantics<RootDatabase>,
561 krate: Option<hir::Crate>,
563 let default = HlTag::UnresolvedReference;
565 let parent = match name.syntax().parent() {
567 _ => return default.into(),
570 match parent.kind() {
571 METHOD_CALL_EXPR => ast::MethodCallExpr::cast(parent)
572 .and_then(|it| highlight_method_call(sema, krate, &it))
573 .unwrap_or_else(|| SymbolKind::Function.into()),
575 let h = HlTag::Symbol(SymbolKind::Field);
576 let is_union = ast::FieldExpr::cast(parent)
577 .and_then(|field_expr| sema.resolve_field(&field_expr))
578 .map_or(false, |field| {
579 matches!(field.parent_def(sema.db), hir::VariantDef::Union(_))
588 let path = match parent.parent().and_then(ast::Path::cast) {
590 _ => return default.into(),
592 let expr = match path.syntax().parent().and_then(ast::PathExpr::cast) {
595 // within path, decide whether it is module or adt by checking for uppercase name
596 return if name.text().chars().next().unwrap_or_default().is_uppercase() {
604 let parent = match expr.syntax().parent() {
606 None => return default.into(),
609 match parent.kind() {
610 CALL_EXPR => SymbolKind::Function.into(),
611 _ => if name.text().chars().next().unwrap_or_default().is_uppercase() {
623 fn is_consumed_lvalue(node: &SyntaxNode, local: &hir::Local, db: &RootDatabase) -> bool {
624 // When lvalues are passed as arguments and they're not Copy, then mark them as Consuming.
625 parents_match(node.clone().into(), &[PATH_SEGMENT, PATH, PATH_EXPR, ARG_LIST])
626 && !local.ty(db).is_copy(db)
629 /// Returns true if the parent nodes of `node` all match the `SyntaxKind`s in `kinds` exactly.
630 fn parents_match(mut node: NodeOrToken<SyntaxNode, SyntaxToken>, mut kinds: &[SyntaxKind]) -> bool {
631 while let (Some(parent), [kind, rest @ ..]) = (&node.parent(), kinds) {
632 if parent.kind() != *kind {
636 // FIXME: Would be nice to get parent out of the match, but binding by-move and by-value
637 // in the same pattern is unstable: rust-lang/rust#68354.
638 node = node.parent().unwrap().into();
642 // Only true if we matched all expected kinds
647 fn parent_matches<N: AstNode>(element: &SyntaxElement) -> bool {
648 element.parent().map_or(false, |it| N::can_cast(it.kind()))
651 fn is_child_of_impl(element: &SyntaxElement) -> bool {
652 match element.parent() {
653 Some(e) => e.kind() == IMPL,