15 use hir::{Name, Semantics};
16 use ide_db::{RootDatabase, SymbolKind};
17 use rustc_hash::FxHashMap;
19 ast::{self, HasFormatSpecifier},
20 AstNode, AstToken, Direction, NodeOrToken,
22 SyntaxNode, TextRange, WalkEvent, T,
26 syntax_highlighting::{
27 format::highlight_format_string, highlights::Highlights,
28 macro_rules::MacroRulesHighlighter, tags::Highlight,
33 pub(crate) use html::highlight_as_html;
35 #[derive(Debug, Clone, Copy)]
38 pub highlight: Highlight,
39 pub binding_hash: Option<u64>,
42 // Feature: Semantic Syntax Highlighting
44 // rust-analyzer highlights the code semantically.
45 // For example, `bar` in `foo::Bar` might be colored differently depending on whether `Bar` is an enum or a trait.
46 // rust-analyzer does not specify colors directly, instead it assigns tag (like `struct`) and a set of modifiers (like `declaration`) to each token.
47 // It's up to the client to map those to specific colors.
49 // The general rule is that a reference to an entity gets colored the same way as the entity itself.
50 // We also give special modifier for `mut` and `&mut` local variables.
51 pub(crate) fn highlight(
54 range_to_highlight: Option<TextRange>,
55 syntactic_name_ref_highlighting: bool,
57 let _p = profile::span("highlight");
58 let sema = Semantics::new(db);
60 // Determine the root based on the given range.
61 let (root, range_to_highlight) = {
62 let source_file = sema.parse(file_id);
63 match range_to_highlight {
65 let node = match source_file.syntax().covering_element(range) {
66 NodeOrToken::Node(it) => it,
67 NodeOrToken::Token(it) => it.parent(),
71 None => (source_file.syntax().clone(), source_file.syntax().text_range()),
75 let mut hl = highlights::Highlights::new(range_to_highlight);
76 traverse(&mut hl, &sema, &root, range_to_highlight, syntactic_name_ref_highlighting);
82 sema: &Semantics<RootDatabase>,
84 range_to_highlight: TextRange,
85 syntactic_name_ref_highlighting: bool,
87 let mut bindings_shadow_count: FxHashMap<Name, u32> = FxHashMap::default();
89 let mut current_macro_call: Option<ast::MacroCall> = None;
90 let mut current_macro_rules: Option<ast::MacroRules> = None;
91 let mut macro_rules_highlighter = MacroRulesHighlighter::default();
92 let mut inside_attribute = false;
94 // Walk all nodes, keeping track of whether we are inside a macro or not.
95 // If in macro, expand it first and highlight the expanded code.
96 for event in root.preorder_with_tokens() {
97 let event_range = match &event {
98 WalkEvent::Enter(it) | WalkEvent::Leave(it) => it.text_range(),
101 // Element outside of the viewport, no need to highlight
102 if range_to_highlight.intersect(event_range).is_none() {
106 // Track "inside macro" state
107 match event.clone().map(|it| it.into_node().and_then(ast::MacroCall::cast)) {
108 WalkEvent::Enter(Some(mc)) => {
109 if let Some(range) = macro_call_range(&mc) {
112 highlight: HlTag::Symbol(SymbolKind::Macro).into(),
116 current_macro_call = Some(mc.clone());
119 WalkEvent::Leave(Some(mc)) => {
120 assert_eq!(current_macro_call, Some(mc));
121 current_macro_call = None;
126 match event.clone().map(|it| it.into_node().and_then(ast::MacroRules::cast)) {
127 WalkEvent::Enter(Some(mac)) => {
128 macro_rules_highlighter.init();
129 current_macro_rules = Some(mac);
132 WalkEvent::Leave(Some(mac)) => {
133 assert_eq!(current_macro_rules, Some(mac));
134 current_macro_rules = None;
135 macro_rules_highlighter = MacroRulesHighlighter::default();
140 WalkEvent::Enter(NodeOrToken::Node(node)) if ast::Attr::can_cast(node.kind()) => {
141 inside_attribute = true
143 WalkEvent::Leave(NodeOrToken::Node(node)) if ast::Attr::can_cast(node.kind()) => {
144 inside_attribute = false
149 let element = match event {
150 WalkEvent::Enter(it) => it,
151 WalkEvent::Leave(it) => {
152 if let Some(node) = it.as_node() {
153 inject::doc_comment(hl, node);
159 let range = element.text_range();
161 if current_macro_rules.is_some() {
162 if let Some(tok) = element.as_token() {
163 macro_rules_highlighter.advance(tok);
167 let element_to_highlight = if current_macro_call.is_some() && element.kind() != COMMENT {
168 // Inside a macro -- expand it first
169 let token = match element.clone().into_token() {
170 Some(it) if it.parent().kind() == TOKEN_TREE => it,
173 let token = sema.descend_into_macros(token.clone());
174 let parent = token.parent();
176 // We only care Name and Name_ref
177 match (token.kind(), parent.kind()) {
178 (IDENT, NAME) | (IDENT, NAME_REF) => parent.into(),
185 if let Some(token) = element.as_token().cloned().and_then(ast::String::cast) {
187 let expanded = element_to_highlight.as_token().unwrap().clone();
188 if inject::ra_fixture(hl, &sema, token, expanded).is_some() {
194 if let Some(_) = macro_rules_highlighter.highlight(element_to_highlight.clone()) {
198 if let Some((mut highlight, binding_hash)) = highlight::element(
200 &mut bindings_shadow_count,
201 syntactic_name_ref_highlighting,
202 element_to_highlight.clone(),
204 if inside_attribute {
205 highlight = highlight | HlMod::Attribute;
208 hl.add(HlRange { range, highlight, binding_hash });
211 if let Some(string) = element_to_highlight.as_token().cloned().and_then(ast::String::cast) {
212 highlight_format_string(hl, &string, range);
213 // Highlight escape sequences
214 if let Some(char_ranges) = string.char_ranges() {
215 for (piece_range, _) in char_ranges.iter().filter(|(_, char)| char.is_ok()) {
216 if string.text()[piece_range.start().into()..].starts_with('\\') {
218 range: piece_range + range.start(),
219 highlight: HlTag::EscapeSequence.into(),
229 fn macro_call_range(macro_call: &ast::MacroCall) -> Option<TextRange> {
230 let path = macro_call.path()?;
231 let name_ref = path.segment()?.name_ref()?;
233 let range_start = name_ref.syntax().text_range().start();
234 let mut range_end = name_ref.syntax().text_range().end();
235 for sibling in path.syntax().siblings_with_tokens(Direction::Next) {
236 match sibling.kind() {
237 T![!] | IDENT => range_end = sibling.text_range().end(),
242 Some(TextRange::new(range_start, range_end))