1 //! Computes color for a single element.
3 use hir::{AsAssocItem, HasVisibility, Semantics};
5 defs::{Definition, IdentClass, NameClass, NameRefClass},
6 FxHashMap, RootDatabase, SymbolKind,
9 ast, match_ast, AstNode, AstToken, NodeOrToken,
10 SyntaxKind::{self, *},
11 SyntaxNode, SyntaxToken, T,
15 syntax_highlighting::tags::{HlOperator, HlPunct},
16 Highlight, HlMod, HlTag,
19 pub(super) fn token(sema: &Semantics<'_, RootDatabase>, token: SyntaxToken) -> Option<Highlight> {
20 if let Some(comment) = ast::Comment::cast(token.clone()) {
21 let h = HlTag::Comment;
22 return Some(match comment.kind().doc {
23 Some(_) => h | HlMod::Documentation,
28 let highlight: Highlight = match token.kind() {
29 STRING | BYTE_STRING => HlTag::StringLiteral.into(),
30 INT_NUMBER if token.parent_ancestors().nth(1).map(|it| it.kind()) == Some(FIELD_EXPR) => {
31 SymbolKind::Field.into()
33 INT_NUMBER | FLOAT_NUMBER => HlTag::NumericLiteral.into(),
34 BYTE => HlTag::ByteLiteral.into(),
35 CHAR => HlTag::CharLiteral.into(),
36 IDENT if token.parent().and_then(ast::TokenTree::cast).is_some() => {
37 // from this point on we are inside a token tree, this only happens for identifiers
38 // that were not mapped down into macro invocations
41 p if p.is_punct() => punctuation(sema, token, p),
42 k if k.is_keyword() => keyword(sema, token, k)?,
48 pub(super) fn name_like(
49 sema: &Semantics<'_, RootDatabase>,
51 bindings_shadow_count: &mut FxHashMap<hir::Name, u32>,
52 syntactic_name_ref_highlighting: bool,
53 name_like: ast::NameLike,
54 ) -> Option<(Highlight, Option<u64>)> {
55 let mut binding_hash = None;
56 let highlight = match name_like {
57 ast::NameLike::NameRef(name_ref) => highlight_name_ref(
60 bindings_shadow_count,
62 syntactic_name_ref_highlighting,
65 ast::NameLike::Name(name) => {
66 highlight_name(sema, bindings_shadow_count, &mut binding_hash, krate, name)
68 ast::NameLike::Lifetime(lifetime) => match IdentClass::classify_lifetime(sema, &lifetime) {
69 Some(IdentClass::NameClass(NameClass::Definition(def))) => {
70 highlight_def(sema, krate, def) | HlMod::Definition
72 Some(IdentClass::NameRefClass(NameRefClass::Definition(def))) => {
73 highlight_def(sema, krate, def)
75 // FIXME: Fallback for 'static and '_, as we do not resolve these yet
76 _ => SymbolKind::LifetimeParam.into(),
79 Some((highlight, binding_hash))
83 sema: &Semantics<'_, RootDatabase>,
87 let parent = token.parent();
88 let parent_kind = parent.as_ref().map_or(EOF, SyntaxNode::kind);
89 match (kind, parent_kind) {
90 (T![?], _) => HlTag::Operator(HlOperator::Other) | HlMod::ControlFlow,
91 (T![&], BIN_EXPR) => HlOperator::Bitwise.into(),
93 let h = HlTag::Operator(HlOperator::Other).into();
94 let is_unsafe = parent
95 .and_then(ast::RefExpr::cast)
96 .map(|ref_expr| sema.is_unsafe_ref_expr(&ref_expr));
97 if let Some(true) = is_unsafe {
103 (T![::] | T![->] | T![=>] | T![..] | T![=] | T![@] | T![.], _) => HlOperator::Other.into(),
104 (T![!], MACRO_CALL | MACRO_RULES) => HlPunct::MacroBang.into(),
105 (T![!], NEVER_TYPE) => HlTag::BuiltinType.into(),
106 (T![!], PREFIX_EXPR) => HlOperator::Logical.into(),
107 (T![*], PTR_TYPE) => HlTag::Keyword.into(),
108 (T![*], PREFIX_EXPR) => {
109 let is_raw_ptr = (|| {
110 let prefix_expr = parent.and_then(ast::PrefixExpr::cast)?;
111 let expr = prefix_expr.expr()?;
112 sema.type_of_expr(&expr)?.original.is_raw_ptr().then(|| ())
114 if let Some(()) = is_raw_ptr {
115 HlTag::Operator(HlOperator::Other) | HlMod::Unsafe
117 HlOperator::Other.into()
120 (T![-], PREFIX_EXPR) => {
121 let prefix_expr = parent.and_then(ast::PrefixExpr::cast).and_then(|e| e.expr());
123 Some(ast::Expr::Literal(_)) => HlTag::NumericLiteral,
124 _ => HlTag::Operator(HlOperator::Other),
128 (T![+] | T![-] | T![*] | T![/] | T![%], BIN_EXPR) => HlOperator::Arithmetic.into(),
129 (T![+=] | T![-=] | T![*=] | T![/=] | T![%=], BIN_EXPR) => {
130 Highlight::from(HlOperator::Arithmetic) | HlMod::Mutable
132 (T![|] | T![&] | T![!] | T![^] | T![>>] | T![<<], BIN_EXPR) => HlOperator::Bitwise.into(),
133 (T![|=] | T![&=] | T![^=] | T![>>=] | T![<<=], BIN_EXPR) => {
134 Highlight::from(HlOperator::Bitwise) | HlMod::Mutable
136 (T![&&] | T![||], BIN_EXPR) => HlOperator::Logical.into(),
137 (T![>] | T![<] | T![==] | T![>=] | T![<=] | T![!=], BIN_EXPR) => {
138 HlOperator::Comparison.into()
140 (_, PREFIX_EXPR | BIN_EXPR | RANGE_EXPR | RANGE_PAT | REST_PAT) => HlOperator::Other.into(),
141 (_, ATTR) => HlTag::AttributeBracket.into(),
142 (kind, _) => match kind {
143 T!['['] | T![']'] => HlPunct::Bracket,
144 T!['{'] | T!['}'] => HlPunct::Brace,
145 T!['('] | T![')'] => HlPunct::Parenthesis,
146 T![<] | T![>] => HlPunct::Angle,
147 T![,] => HlPunct::Comma,
148 T![:] => HlPunct::Colon,
149 T![;] => HlPunct::Semi,
150 T![.] => HlPunct::Dot,
158 sema: &Semantics<'_, RootDatabase>,
161 ) -> Option<Highlight> {
162 let h = Highlight::new(HlTag::Keyword);
164 T![await] => h | HlMod::Async | HlMod::ControlFlow,
165 T![async] => h | HlMod::Async,
175 | T![yield] => h | HlMod::ControlFlow,
176 T![for] if parent_matches::<ast::ForExpr>(&token) => h | HlMod::ControlFlow,
177 T![unsafe] => h | HlMod::Unsafe,
178 T![true] | T![false] => HlTag::BoolLiteral.into(),
179 // crate is handled just as a token if it's in an `extern crate`
180 T![crate] if parent_matches::<ast::ExternCrate>(&token) => h,
181 // self, crate, super and `Self` are handled as either a Name or NameRef already, unless they
182 // are inside unmapped token trees
183 T![self] | T![crate] | T![super] | T![Self] if parent_matches::<ast::NameRef>(&token) => {
186 T![self] if parent_matches::<ast::Name>(&token) => return None,
187 T![ref] => match token.parent().and_then(ast::IdentPat::cast) {
188 Some(ident) if sema.is_unsafe_ident_pat(&ident) => h | HlMod::Unsafe,
196 fn highlight_name_ref(
197 sema: &Semantics<'_, RootDatabase>,
199 bindings_shadow_count: &mut FxHashMap<hir::Name, u32>,
200 binding_hash: &mut Option<u64>,
201 syntactic_name_ref_highlighting: bool,
202 name_ref: ast::NameRef,
205 if let Some(res) = highlight_method_call_by_name_ref(sema, krate, &name_ref) {
209 let name_class = match NameRefClass::classify(sema, &name_ref) {
210 Some(name_kind) => name_kind,
211 None if syntactic_name_ref_highlighting => {
212 return highlight_name_ref_by_syntax(name_ref, sema, krate)
214 // FIXME: This is required for helper attributes used by proc-macros, as those do not map down
215 // to anything when used.
216 // We can fix this for derive attributes since derive helpers are recorded, but not for
217 // general attributes.
218 None if name_ref.syntax().ancestors().any(|it| it.kind() == ATTR) => {
219 return HlTag::Symbol(SymbolKind::Attribute).into();
221 None => return HlTag::UnresolvedReference.into(),
223 let mut h = match name_class {
224 NameRefClass::Definition(def) => {
225 if let Definition::Local(local) = &def {
226 let name = local.name(db);
227 let shadow_count = bindings_shadow_count.entry(name.clone()).or_default();
228 *binding_hash = Some(calc_binding_hash(&name, *shadow_count))
231 let mut h = highlight_def(sema, krate, def);
234 Definition::Local(local) if is_consumed_lvalue(name_ref.syntax(), &local, db) => {
235 h |= HlMod::Consuming;
237 Definition::Trait(trait_) if trait_.is_unsafe(db) => {
238 if ast::Impl::for_trait_name_ref(&name_ref)
239 .map_or(false, |impl_| impl_.unsafe_token().is_some())
244 Definition::Field(field) => {
245 if let Some(parent) = name_ref.syntax().parent() {
246 if matches!(parent.kind(), FIELD_EXPR | RECORD_PAT_FIELD) {
247 if let hir::VariantDef::Union(_) = field.parent_def(db) {
253 Definition::Macro(_) => {
254 if let Some(macro_call) =
255 ide_db::syntax_helpers::node_ext::full_path_of_name_ref(&name_ref)
256 .and_then(|it| it.syntax().parent().and_then(ast::MacroCall::cast))
258 if sema.is_unsafe_macro_call(¯o_call) {
268 NameRefClass::FieldShorthand { .. } => SymbolKind::Field.into(),
271 h.tag = match name_ref.token_kind() {
272 T![Self] => HlTag::Symbol(SymbolKind::SelfType),
273 T![self] => HlTag::Symbol(SymbolKind::SelfParam),
274 T![super] | T![crate] => HlTag::Keyword,
281 sema: &Semantics<'_, RootDatabase>,
282 bindings_shadow_count: &mut FxHashMap<hir::Name, u32>,
283 binding_hash: &mut Option<u64>,
287 let name_kind = NameClass::classify(sema, &name);
288 if let Some(NameClass::Definition(Definition::Local(local))) = &name_kind {
289 let name = local.name(sema.db);
290 let shadow_count = bindings_shadow_count.entry(name.clone()).or_default();
292 *binding_hash = Some(calc_binding_hash(&name, *shadow_count))
295 Some(NameClass::Definition(def)) => {
296 let mut h = highlight_def(sema, krate, def) | HlMod::Definition;
297 if let Definition::Trait(trait_) = &def {
298 if trait_.is_unsafe(sema.db) {
304 Some(NameClass::ConstReference(def)) => highlight_def(sema, krate, def),
305 Some(NameClass::PatFieldShorthand { field_ref, .. }) => {
306 let mut h = HlTag::Symbol(SymbolKind::Field).into();
307 if let hir::VariantDef::Union(_) = field_ref.parent_def(sema.db) {
312 None => highlight_name_by_syntax(name) | HlMod::Definition,
316 fn calc_binding_hash(name: &hir::Name, shadow_count: u32) -> u64 {
317 fn hash<T: std::hash::Hash + std::fmt::Debug>(x: T) -> u64 {
318 use std::{collections::hash_map::DefaultHasher, hash::Hasher};
320 let mut hasher = DefaultHasher::new();
325 hash((name, shadow_count))
329 sema: &Semantics<'_, RootDatabase>,
334 let mut h = match def {
335 Definition::Macro(m) => Highlight::new(HlTag::Symbol(m.kind(sema.db).into())),
336 Definition::Field(_) => Highlight::new(HlTag::Symbol(SymbolKind::Field)),
337 Definition::Module(module) => {
338 let mut h = Highlight::new(HlTag::Symbol(SymbolKind::Module));
339 if module.is_crate_root(db) {
340 h |= HlMod::CrateRoot;
344 Definition::Function(func) => {
345 let mut h = Highlight::new(HlTag::Symbol(SymbolKind::Function));
346 if let Some(item) = func.as_assoc_item(db) {
347 h |= HlMod::Associated;
348 match func.self_param(db) {
349 Some(sp) => match sp.access(db) {
350 hir::Access::Exclusive => {
352 h |= HlMod::Reference;
354 hir::Access::Shared => h |= HlMod::Reference,
355 hir::Access::Owned => h |= HlMod::Consuming,
357 None => h |= HlMod::Static,
360 match item.container(db) {
361 hir::AssocItemContainer::Impl(i) => {
362 if i.trait_(db).is_some() {
366 hir::AssocItemContainer::Trait(_t) => {
372 if func.is_unsafe_to_call(db) {
375 if func.is_async(db) {
381 Definition::Adt(adt) => {
383 hir::Adt::Struct(_) => HlTag::Symbol(SymbolKind::Struct),
384 hir::Adt::Enum(_) => HlTag::Symbol(SymbolKind::Enum),
385 hir::Adt::Union(_) => HlTag::Symbol(SymbolKind::Union),
390 Definition::Variant(_) => Highlight::new(HlTag::Symbol(SymbolKind::Variant)),
391 Definition::Const(konst) => {
392 let mut h = Highlight::new(HlTag::Symbol(SymbolKind::Const));
394 if let Some(item) = konst.as_assoc_item(db) {
395 h |= HlMod::Associated;
396 match item.container(db) {
397 hir::AssocItemContainer::Impl(i) => {
398 if i.trait_(db).is_some() {
402 hir::AssocItemContainer::Trait(_t) => {
410 Definition::Trait(_) => Highlight::new(HlTag::Symbol(SymbolKind::Trait)),
411 Definition::TypeAlias(type_) => {
412 let mut h = Highlight::new(HlTag::Symbol(SymbolKind::TypeAlias));
414 if let Some(item) = type_.as_assoc_item(db) {
415 h |= HlMod::Associated;
416 match item.container(db) {
417 hir::AssocItemContainer::Impl(i) => {
418 if i.trait_(db).is_some() {
422 hir::AssocItemContainer::Trait(_t) => {
430 Definition::BuiltinType(_) => Highlight::new(HlTag::BuiltinType),
431 Definition::Static(s) => {
432 let mut h = Highlight::new(HlTag::Symbol(SymbolKind::Static));
441 Definition::SelfType(_) => Highlight::new(HlTag::Symbol(SymbolKind::Impl)),
442 Definition::GenericParam(it) => match it {
443 hir::GenericParam::TypeParam(_) => Highlight::new(HlTag::Symbol(SymbolKind::TypeParam)),
444 hir::GenericParam::ConstParam(_) => {
445 Highlight::new(HlTag::Symbol(SymbolKind::ConstParam))
447 hir::GenericParam::LifetimeParam(_) => {
448 Highlight::new(HlTag::Symbol(SymbolKind::LifetimeParam))
451 Definition::Local(local) => {
452 let tag = if local.is_self(db) {
453 HlTag::Symbol(SymbolKind::SelfParam)
454 } else if local.is_param(db) {
455 HlTag::Symbol(SymbolKind::ValueParam)
457 HlTag::Symbol(SymbolKind::Local)
459 let mut h = Highlight::new(tag);
460 let ty = local.ty(db);
461 if local.is_mut(db) || ty.is_mutable_reference() {
464 if local.is_ref(db) || ty.is_reference() {
465 h |= HlMod::Reference;
467 if ty.as_callable(db).is_some() || ty.impls_fnonce(db) {
468 h |= HlMod::Callable;
472 Definition::Label(_) => Highlight::new(HlTag::Symbol(SymbolKind::Label)),
473 Definition::BuiltinAttr(_) => Highlight::new(HlTag::Symbol(SymbolKind::BuiltinAttr)),
474 Definition::ToolModule(_) => Highlight::new(HlTag::Symbol(SymbolKind::ToolModule)),
475 Definition::DeriveHelper(_) => Highlight::new(HlTag::Symbol(SymbolKind::DeriveHelper)),
478 let def_crate = def.krate(db);
479 let is_from_other_crate = def_crate != Some(krate);
480 let is_from_builtin_crate = def_crate.map_or(false, |def_crate| def_crate.is_builtin(db));
481 let is_builtin_type = matches!(def, Definition::BuiltinType(_));
482 let is_public = def.visibility(db) == Some(hir::Visibility::Public);
484 match (is_from_other_crate, is_builtin_type, is_public) {
485 (true, false, _) => h |= HlMod::Library,
486 (false, _, true) => h |= HlMod::Public,
490 if is_from_builtin_crate {
491 h |= HlMod::DefaultLibrary;
497 fn highlight_method_call_by_name_ref(
498 sema: &Semantics<'_, RootDatabase>,
500 name_ref: &ast::NameRef,
501 ) -> Option<Highlight> {
502 let mc = name_ref.syntax().parent().and_then(ast::MethodCallExpr::cast)?;
503 highlight_method_call(sema, krate, &mc)
506 fn highlight_method_call(
507 sema: &Semantics<'_, RootDatabase>,
509 method_call: &ast::MethodCallExpr,
510 ) -> Option<Highlight> {
511 let func = sema.resolve_method_call(method_call)?;
513 let mut h = SymbolKind::Function.into();
514 h |= HlMod::Associated;
516 if func.is_unsafe_to_call(sema.db) || sema.is_unsafe_method_call(method_call) {
519 if func.is_async(sema.db) {
523 .as_assoc_item(sema.db)
524 .and_then(|it| it.containing_trait_or_trait_impl(sema.db))
530 let def_crate = func.module(sema.db).krate();
531 let is_from_other_crate = def_crate != krate;
532 let is_from_builtin_crate = def_crate.is_builtin(sema.db);
533 let is_public = func.visibility(sema.db) == hir::Visibility::Public;
535 if is_from_other_crate {
537 } else if is_public {
541 if is_from_builtin_crate {
542 h |= HlMod::DefaultLibrary;
545 if let Some(self_param) = func.self_param(sema.db) {
546 match self_param.access(sema.db) {
547 hir::Access::Shared => h |= HlMod::Reference,
548 hir::Access::Exclusive => {
550 h |= HlMod::Reference;
552 hir::Access::Owned => {
553 if let Some(receiver_ty) =
554 method_call.receiver().and_then(|it| sema.type_of_expr(&it))
556 if !receiver_ty.adjusted().is_copy(sema.db) {
557 h |= HlMod::Consuming
566 fn highlight_name_by_syntax(name: ast::Name) -> Highlight {
567 let default = HlTag::UnresolvedReference;
569 let parent = match name.syntax().parent() {
571 _ => return default.into(),
574 let tag = match parent.kind() {
575 STRUCT => SymbolKind::Struct,
576 ENUM => SymbolKind::Enum,
577 VARIANT => SymbolKind::Variant,
578 UNION => SymbolKind::Union,
579 TRAIT => SymbolKind::Trait,
580 TYPE_ALIAS => SymbolKind::TypeAlias,
581 TYPE_PARAM => SymbolKind::TypeParam,
582 RECORD_FIELD => SymbolKind::Field,
583 MODULE => SymbolKind::Module,
584 FN => SymbolKind::Function,
585 CONST => SymbolKind::Const,
586 STATIC => SymbolKind::Static,
587 IDENT_PAT => SymbolKind::Local,
588 _ => return default.into(),
594 fn highlight_name_ref_by_syntax(
596 sema: &Semantics<'_, RootDatabase>,
599 let default = HlTag::UnresolvedReference;
601 let parent = match name.syntax().parent() {
603 _ => return default.into(),
606 match parent.kind() {
607 METHOD_CALL_EXPR => ast::MethodCallExpr::cast(parent)
608 .and_then(|it| highlight_method_call(sema, krate, &it))
609 .unwrap_or_else(|| SymbolKind::Function.into()),
611 let h = HlTag::Symbol(SymbolKind::Field);
612 let is_union = ast::FieldExpr::cast(parent)
613 .and_then(|field_expr| sema.resolve_field(&field_expr))
614 .map_or(false, |field| {
615 matches!(field.parent_def(sema.db), hir::VariantDef::Union(_))
624 let name_based_fallback = || {
625 if name.text().chars().next().unwrap_or_default().is_uppercase() {
626 SymbolKind::Struct.into()
628 SymbolKind::Module.into()
631 let path = match parent.parent().and_then(ast::Path::cast) {
633 _ => return name_based_fallback(),
635 let expr = match path.syntax().parent() {
636 Some(parent) => match_ast! {
638 ast::PathExpr(path) => path,
639 ast::MacroCall(_) => return SymbolKind::Macro.into(),
640 _ => return name_based_fallback(),
643 // within path, decide whether it is module or adt by checking for uppercase name
644 None => return name_based_fallback(),
646 let parent = match expr.syntax().parent() {
648 None => return default.into(),
651 match parent.kind() {
652 CALL_EXPR => SymbolKind::Function.into(),
653 _ => if name.text().chars().next().unwrap_or_default().is_uppercase() {
665 fn is_consumed_lvalue(node: &SyntaxNode, local: &hir::Local, db: &RootDatabase) -> bool {
666 // When lvalues are passed as arguments and they're not Copy, then mark them as Consuming.
667 parents_match(node.clone().into(), &[PATH_SEGMENT, PATH, PATH_EXPR, ARG_LIST])
668 && !local.ty(db).is_copy(db)
671 /// Returns true if the parent nodes of `node` all match the `SyntaxKind`s in `kinds` exactly.
672 fn parents_match(mut node: NodeOrToken<SyntaxNode, SyntaxToken>, mut kinds: &[SyntaxKind]) -> bool {
673 while let (Some(parent), [kind, rest @ ..]) = (&node.parent(), kinds) {
674 if parent.kind() != *kind {
678 // FIXME: Would be nice to get parent out of the match, but binding by-move and by-value
679 // in the same pattern is unstable: rust-lang/rust#68354.
680 node = node.parent().unwrap().into();
684 // Only true if we matched all expected kinds
688 fn parent_matches<N: AstNode>(token: &SyntaxToken) -> bool {
689 token.parent().map_or(false, |it| N::can_cast(it.kind()))