7 use hir::{Name, Semantics};
9 defs::{classify_name, classify_name_ref, Definition, NameClass, NameRefClass},
14 ast::{self, HasFormatSpecifier},
15 AstNode, AstToken, Direction, NodeOrToken, SyntaxElement,
17 TextRange, WalkEvent, T,
19 use rustc_hash::FxHashMap;
23 use ast::FormatSpecifier;
24 pub(crate) use html::highlight_as_html;
25 pub use tags::{Highlight, HighlightModifier, HighlightModifiers, HighlightTag};
27 #[derive(Debug, Clone)]
28 pub struct HighlightedRange {
30 pub highlight: Highlight,
31 pub binding_hash: Option<u64>,
34 // Feature: Semantic Syntax Highlighting
36 // rust-analyzer highlights the code semantically.
37 // For example, `bar` in `foo::Bar` might be colored differently depending on whether `Bar` is an enum or a trait.
38 // rust-analyzer does not specify colors directly, instead it assigns tag (like `struct`) and a set of modifiers (like `declaration`) to each token.
39 // It's up to the client to map those to specific colors.
41 // The general rule is that a reference to an entity gets colored the same way as the entity itself.
42 // We also give special modifier for `mut` and `&mut` local variables.
43 pub(crate) fn highlight(
46 range_to_highlight: Option<TextRange>,
47 syntactic_name_ref_highlighting: bool,
48 ) -> Vec<HighlightedRange> {
49 let _p = profile("highlight");
50 let sema = Semantics::new(db);
52 // Determine the root based on the given range.
53 let (root, range_to_highlight) = {
54 let source_file = sema.parse(file_id);
55 match range_to_highlight {
57 let node = match source_file.syntax().covering_element(range) {
58 NodeOrToken::Node(it) => it,
59 NodeOrToken::Token(it) => it.parent(),
63 None => (source_file.syntax().clone(), source_file.syntax().text_range()),
67 let mut bindings_shadow_count: FxHashMap<Name, u32> = FxHashMap::default();
68 // We use a stack for the DFS traversal below.
69 // When we leave a node, the we use it to flatten the highlighted ranges.
70 let mut stack = HighlightedRangeStack::new();
72 let mut current_macro_call: Option<ast::MacroCall> = None;
73 let mut format_string: Option<SyntaxElement> = None;
75 // Walk all nodes, keeping track of whether we are inside a macro or not.
76 // If in macro, expand it first and highlight the expanded code.
77 for event in root.preorder_with_tokens() {
79 WalkEvent::Enter(_) => stack.push(),
80 WalkEvent::Leave(_) => stack.pop(),
83 let event_range = match &event {
84 WalkEvent::Enter(it) => it.text_range(),
85 WalkEvent::Leave(it) => it.text_range(),
88 // Element outside of the viewport, no need to highlight
89 if range_to_highlight.intersect(event_range).is_none() {
93 // Track "inside macro" state
94 match event.clone().map(|it| it.into_node().and_then(ast::MacroCall::cast)) {
95 WalkEvent::Enter(Some(mc)) => {
96 current_macro_call = Some(mc.clone());
97 if let Some(range) = macro_call_range(&mc) {
98 stack.add(HighlightedRange {
100 highlight: HighlightTag::Macro.into(),
104 if let Some(name) = mc.is_macro_rules() {
105 if let Some((highlight, binding_hash)) = highlight_element(
107 &mut bindings_shadow_count,
108 syntactic_name_ref_highlighting,
109 name.syntax().clone().into(),
111 stack.add(HighlightedRange {
112 range: name.syntax().text_range(),
120 WalkEvent::Leave(Some(mc)) => {
121 assert!(current_macro_call == Some(mc));
122 current_macro_call = None;
123 format_string = None;
129 // Check for Rust code in documentation
131 WalkEvent::Leave(NodeOrToken::Node(node)) => {
132 if let Some((doctest, range_mapping, new_comments)) =
133 injection::extract_doc_comments(node)
135 injection::highlight_doc_comment(
146 let element = match event {
147 WalkEvent::Enter(it) => it,
148 WalkEvent::Leave(_) => continue,
151 let range = element.text_range();
153 let element_to_highlight = if current_macro_call.is_some() {
154 // Inside a macro -- expand it first
155 let token = match element.clone().into_token() {
156 Some(it) if it.parent().kind() == TOKEN_TREE => it,
159 let token = sema.descend_into_macros(token.clone());
160 let parent = token.parent();
162 // Check if macro takes a format string and remember it for highlighting later.
163 // The macros that accept a format string expand to a compiler builtin macros
164 // `format_args` and `format_args_nl`.
165 if let Some(name) = parent
167 .and_then(ast::MacroCall::cast)
168 .and_then(|mc| mc.path())
169 .and_then(|p| p.segment())
170 .and_then(|s| s.name_ref())
172 match name.text().as_str() {
173 "format_args" | "format_args_nl" => {
174 format_string = parent
175 .children_with_tokens()
176 .filter(|t| t.kind() != WHITESPACE)
179 ast::String::can_cast(e.kind())
180 || ast::RawString::can_cast(e.kind())
187 // We only care Name and Name_ref
188 match (token.kind(), parent.kind()) {
189 (IDENT, NAME) | (IDENT, NAME_REF) => parent.into(),
196 if let Some(token) = element.as_token().cloned().and_then(ast::RawString::cast) {
197 let expanded = element_to_highlight.as_token().unwrap().clone();
198 if injection::highlight_injection(&mut stack, &sema, token, expanded).is_some() {
203 let is_format_string = format_string.as_ref() == Some(&element_to_highlight);
205 if let Some((highlight, binding_hash)) = highlight_element(
207 &mut bindings_shadow_count,
208 syntactic_name_ref_highlighting,
209 element_to_highlight.clone(),
211 stack.add(HighlightedRange { range, highlight, binding_hash });
212 if let Some(string) =
213 element_to_highlight.as_token().cloned().and_then(ast::String::cast)
216 if is_format_string {
217 string.lex_format_specifier(|piece_range, kind| {
218 if let Some(highlight) = highlight_format_specifier(kind) {
219 stack.add(HighlightedRange {
220 range: piece_range + range.start(),
221 highlight: highlight.into(),
228 } else if let Some(string) =
229 element_to_highlight.as_token().cloned().and_then(ast::RawString::cast)
232 if is_format_string {
233 string.lex_format_specifier(|piece_range, kind| {
234 if let Some(highlight) = highlight_format_specifier(kind) {
235 stack.add(HighlightedRange {
236 range: piece_range + range.start(),
237 highlight: highlight.into(),
252 struct HighlightedRangeStack {
253 stack: Vec<Vec<HighlightedRange>>,
256 /// We use a stack to implement the flattening logic for the highlighted
258 impl HighlightedRangeStack {
260 Self { stack: vec![Vec::new()] }
264 self.stack.push(Vec::new());
267 /// Flattens the highlighted ranges.
269 /// For example `#[cfg(feature = "foo")]` contains the nested ranges:
270 /// 1) parent-range: Attribute [0, 23)
271 /// 2) child-range: String [16, 21)
273 /// The following code implements the flattening, for our example this results to:
274 /// `[Attribute [0, 16), String [16, 21), Attribute [21, 23)]`
276 let children = self.stack.pop().unwrap();
277 let prev = self.stack.last_mut().unwrap();
278 let needs_flattening = !children.is_empty()
280 && prev.last().unwrap().range.contains_range(children.first().unwrap().range);
281 if !needs_flattening {
282 prev.extend(children);
284 let mut parent = prev.pop().unwrap();
285 for ele in children {
286 assert!(parent.range.contains_range(ele.range));
288 let cloned = Self::intersect(&mut parent, &ele);
289 if !parent.range.is_empty() {
295 if !parent.range.is_empty() {
301 /// Intersects the `HighlightedRange` `parent` with `child`.
302 /// `parent` is mutated in place, becoming the range before `child`.
303 /// Returns the range (of the same type as `parent`) *after* `child`.
304 fn intersect(parent: &mut HighlightedRange, child: &HighlightedRange) -> HighlightedRange {
305 assert!(parent.range.contains_range(child.range));
307 let mut cloned = parent.clone();
308 parent.range = TextRange::new(parent.range.start(), child.range.start());
309 cloned.range = TextRange::new(child.range.end(), cloned.range.end());
314 /// Similar to `pop`, but can modify arbitrary prior ranges (where `pop`)
315 /// can only modify the last range currently on the stack.
316 /// Can be used to do injections that span multiple ranges, like the
317 /// doctest injection below.
318 /// If `delete` is set to true, the parent range is deleted instead of
321 /// Note that `pop` can be simulated by `pop_and_inject(false)` but the
322 /// latter is computationally more expensive.
323 fn pop_and_inject(&mut self, delete: bool) {
324 let mut children = self.stack.pop().unwrap();
325 let prev = self.stack.last_mut().unwrap();
326 children.sort_by_key(|range| range.range.start());
327 prev.sort_by_key(|range| range.range.start());
329 for child in children {
331 prev.iter().position(|parent| parent.range.contains_range(child.range))
333 let cloned = Self::intersect(&mut prev[idx], &child);
334 let insert_idx = if delete || prev[idx].range.is_empty() {
340 prev.insert(insert_idx, child);
341 if !delete && !cloned.range.is_empty() {
342 prev.insert(insert_idx + 1, cloned);
344 } else if let Some(_idx) =
345 prev.iter().position(|parent| parent.range.contains(child.range.start()))
347 unreachable!("child range should be completely contained in parent range");
350 .binary_search_by_key(&child.range.start(), |range| range.range.start())
351 .unwrap_or_else(|x| x);
352 prev.insert(idx, child);
357 fn add(&mut self, range: HighlightedRange) {
360 .expect("during DFS traversal, the stack must not be empty")
364 fn flattened(mut self) -> Vec<HighlightedRange> {
368 "after DFS traversal, the stack should only contain a single element"
370 let mut res = self.stack.pop().unwrap();
371 res.sort_by_key(|range| range.range.start());
372 // Check that ranges are sorted and disjoint
375 .zip(res.iter().skip(1))
376 .all(|(left, right)| left.range.end() <= right.range.start()));
381 fn highlight_format_specifier(kind: FormatSpecifier) -> Option<HighlightTag> {
383 FormatSpecifier::Open
384 | FormatSpecifier::Close
385 | FormatSpecifier::Colon
386 | FormatSpecifier::Fill
387 | FormatSpecifier::Align
388 | FormatSpecifier::Sign
389 | FormatSpecifier::NumberSign
390 | FormatSpecifier::DollarSign
391 | FormatSpecifier::Dot
392 | FormatSpecifier::Asterisk
393 | FormatSpecifier::QuestionMark => HighlightTag::FormatSpecifier,
394 FormatSpecifier::Integer | FormatSpecifier::Zero => HighlightTag::NumericLiteral,
395 FormatSpecifier::Identifier => HighlightTag::Local,
399 fn macro_call_range(macro_call: &ast::MacroCall) -> Option<TextRange> {
400 let path = macro_call.path()?;
401 let name_ref = path.segment()?.name_ref()?;
403 let range_start = name_ref.syntax().text_range().start();
404 let mut range_end = name_ref.syntax().text_range().end();
405 for sibling in path.syntax().siblings_with_tokens(Direction::Next) {
406 match sibling.kind() {
407 T![!] | IDENT => range_end = sibling.text_range().end(),
412 Some(TextRange::new(range_start, range_end))
415 fn highlight_element(
416 sema: &Semantics<RootDatabase>,
417 bindings_shadow_count: &mut FxHashMap<Name, u32>,
418 syntactic_name_ref_highlighting: bool,
419 element: SyntaxElement,
420 ) -> Option<(Highlight, Option<u64>)> {
422 let mut binding_hash = None;
423 let highlight: Highlight = match element.kind() {
425 bindings_shadow_count.clear();
429 // Highlight definitions depending on the "type" of the definition.
431 let name = element.into_node().and_then(ast::Name::cast).unwrap();
432 let name_kind = classify_name(sema, &name);
434 if let Some(NameClass::Definition(Definition::Local(local))) = &name_kind {
435 if let Some(name) = local.name(db) {
436 let shadow_count = bindings_shadow_count.entry(name.clone()).or_default();
438 binding_hash = Some(calc_binding_hash(&name, *shadow_count))
443 Some(NameClass::Definition(def)) => {
444 highlight_name(db, def) | HighlightModifier::Definition
446 Some(NameClass::ConstReference(def)) => highlight_name(db, def),
447 Some(NameClass::FieldShorthand { .. }) => HighlightTag::Field.into(),
448 None => highlight_name_by_syntax(name) | HighlightModifier::Definition,
452 // Highlight references like the definitions they resolve to
453 NAME_REF if element.ancestors().any(|it| it.kind() == ATTR) => {
454 Highlight::from(HighlightTag::Function) | HighlightModifier::Attribute
457 let name_ref = element.into_node().and_then(ast::NameRef::cast).unwrap();
458 match classify_name_ref(sema, &name_ref) {
459 Some(name_kind) => match name_kind {
460 NameRefClass::Definition(def) => {
461 if let Definition::Local(local) = &def {
462 if let Some(name) = local.name(db) {
464 bindings_shadow_count.entry(name.clone()).or_default();
465 binding_hash = Some(calc_binding_hash(&name, *shadow_count))
468 highlight_name(db, def)
470 NameRefClass::FieldShorthand { .. } => HighlightTag::Field.into(),
472 None if syntactic_name_ref_highlighting => highlight_name_ref_by_syntax(name_ref),
473 None => HighlightTag::UnresolvedReference.into(),
477 // Simple token-based highlighting
478 COMMENT => HighlightTag::Comment.into(),
479 STRING | RAW_STRING | RAW_BYTE_STRING | BYTE_STRING => HighlightTag::StringLiteral.into(),
480 ATTR => HighlightTag::Attribute.into(),
481 INT_NUMBER | FLOAT_NUMBER => HighlightTag::NumericLiteral.into(),
482 BYTE => HighlightTag::ByteLiteral.into(),
483 CHAR => HighlightTag::CharLiteral.into(),
484 QUESTION => Highlight::new(HighlightTag::Operator) | HighlightModifier::ControlFlow,
486 let h = Highlight::new(HighlightTag::Lifetime);
487 match element.parent().map(|it| it.kind()) {
488 Some(LIFETIME_PARAM) | Some(LABEL) => h | HighlightModifier::Definition,
493 let prefix_expr = element.parent().and_then(ast::PrefixExpr::cast)?;
495 let expr = prefix_expr.expr()?;
496 let ty = sema.type_of_expr(&expr)?;
497 if !ty.is_raw_ptr() {
501 let mut h = Highlight::new(HighlightTag::Operator);
502 h |= HighlightModifier::Unsafe;
505 T![!] if element.parent().and_then(ast::MacroCall::cast).is_some() => {
506 Highlight::new(HighlightTag::Macro)
509 k if k.is_keyword() => {
510 let h = Highlight::new(HighlightTag::Keyword);
520 | T![in] => h | HighlightModifier::ControlFlow,
521 T![for] if !is_child_of_impl(element) => h | HighlightModifier::ControlFlow,
522 T![unsafe] => h | HighlightModifier::Unsafe,
523 T![true] | T![false] => HighlightTag::BoolLiteral.into(),
524 T![self] => HighlightTag::SelfKeyword.into(),
532 return Some((highlight, binding_hash));
534 fn calc_binding_hash(name: &Name, shadow_count: u32) -> u64 {
535 fn hash<T: std::hash::Hash + std::fmt::Debug>(x: T) -> u64 {
536 use std::{collections::hash_map::DefaultHasher, hash::Hasher};
538 let mut hasher = DefaultHasher::new();
543 hash((name, shadow_count))
547 fn is_child_of_impl(element: SyntaxElement) -> bool {
548 match element.parent() {
549 Some(e) => e.kind() == IMPL_DEF,
554 fn highlight_name(db: &RootDatabase, def: Definition) -> Highlight {
556 Definition::Macro(_) => HighlightTag::Macro,
557 Definition::Field(_) => HighlightTag::Field,
558 Definition::ModuleDef(def) => match def {
559 hir::ModuleDef::Module(_) => HighlightTag::Module,
560 hir::ModuleDef::Function(func) => {
561 let mut h = HighlightTag::Function.into();
562 if func.is_unsafe(db) {
563 h |= HighlightModifier::Unsafe;
567 hir::ModuleDef::Adt(hir::Adt::Struct(_)) => HighlightTag::Struct,
568 hir::ModuleDef::Adt(hir::Adt::Enum(_)) => HighlightTag::Enum,
569 hir::ModuleDef::Adt(hir::Adt::Union(_)) => HighlightTag::Union,
570 hir::ModuleDef::EnumVariant(_) => HighlightTag::EnumVariant,
571 hir::ModuleDef::Const(_) => HighlightTag::Constant,
572 hir::ModuleDef::Trait(_) => HighlightTag::Trait,
573 hir::ModuleDef::TypeAlias(_) => HighlightTag::TypeAlias,
574 hir::ModuleDef::BuiltinType(_) => HighlightTag::BuiltinType,
575 hir::ModuleDef::Static(s) => {
576 let mut h = Highlight::new(HighlightTag::Static);
578 h |= HighlightModifier::Mutable;
583 Definition::SelfType(_) => HighlightTag::SelfType,
584 Definition::TypeParam(_) => HighlightTag::TypeParam,
585 // FIXME: distinguish between locals and parameters
586 Definition::Local(local) => {
587 let mut h = Highlight::new(HighlightTag::Local);
588 if local.is_mut(db) || local.ty(db).is_mutable_reference() {
589 h |= HighlightModifier::Mutable;
597 fn highlight_name_by_syntax(name: ast::Name) -> Highlight {
598 let default = HighlightTag::UnresolvedReference;
600 let parent = match name.syntax().parent() {
602 _ => return default.into(),
605 let tag = match parent.kind() {
606 STRUCT_DEF => HighlightTag::Struct,
607 ENUM_DEF => HighlightTag::Enum,
608 UNION_DEF => HighlightTag::Union,
609 TRAIT_DEF => HighlightTag::Trait,
610 TYPE_ALIAS_DEF => HighlightTag::TypeAlias,
611 TYPE_PARAM => HighlightTag::TypeParam,
612 RECORD_FIELD_DEF => HighlightTag::Field,
613 MODULE => HighlightTag::Module,
614 FN_DEF => HighlightTag::Function,
615 CONST_DEF => HighlightTag::Constant,
616 STATIC_DEF => HighlightTag::Static,
617 ENUM_VARIANT => HighlightTag::EnumVariant,
618 BIND_PAT => HighlightTag::Local,
625 fn highlight_name_ref_by_syntax(name: ast::NameRef) -> Highlight {
626 let default = HighlightTag::UnresolvedReference;
628 let parent = match name.syntax().parent() {
630 _ => return default.into(),
633 let tag = match parent.kind() {
634 METHOD_CALL_EXPR => HighlightTag::Function,
635 FIELD_EXPR => HighlightTag::Field,
637 let path = match parent.parent().and_then(ast::Path::cast) {
639 _ => return default.into(),
641 let expr = match path.syntax().parent().and_then(ast::PathExpr::cast) {
644 // within path, decide whether it is module or adt by checking for uppercase name
645 return if name.text().chars().next().unwrap_or_default().is_uppercase() {
653 let parent = match expr.syntax().parent() {
655 None => return default.into(),
658 match parent.kind() {
659 CALL_EXPR => HighlightTag::Function,
661 if name.text().chars().next().unwrap_or_default().is_uppercase() {
664 HighlightTag::Constant