15 use hir::{InFile, 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, macro_::MacroHighlighter,
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.
52 // image::https://user-images.githubusercontent.com/48062697/113164457-06cfb980-9239-11eb-819b-0f93e646acf8.png[]
53 // image::https://user-images.githubusercontent.com/48062697/113187625-f7f50100-9250-11eb-825e-91c58f236071.png[]
54 pub(crate) fn highlight(
57 range_to_highlight: Option<TextRange>,
58 syntactic_name_ref_highlighting: bool,
60 let _p = profile::span("highlight");
61 let sema = Semantics::new(db);
63 // Determine the root based on the given range.
64 let (root, range_to_highlight) = {
65 let source_file = sema.parse(file_id);
66 match range_to_highlight {
68 let node = match source_file.syntax().covering_element(range) {
69 NodeOrToken::Node(it) => it,
70 NodeOrToken::Token(it) => it.parent().unwrap(),
74 None => (source_file.syntax().clone(), source_file.syntax().text_range()),
78 let mut hl = highlights::Highlights::new(root.text_range());
82 InFile::new(file_id.into(), &root),
84 syntactic_name_ref_highlighting,
91 sema: &Semantics<RootDatabase>,
92 root: InFile<&SyntaxNode>,
93 range_to_highlight: TextRange,
94 syntactic_name_ref_highlighting: bool,
96 let mut bindings_shadow_count: FxHashMap<Name, u32> = FxHashMap::default();
98 let mut current_macro_call: Option<ast::MacroCall> = None;
99 let mut current_macro: Option<ast::Macro> = None;
100 let mut macro_highlighter = MacroHighlighter::default();
101 let mut inside_attribute = false;
103 // Walk all nodes, keeping track of whether we are inside a macro or not.
104 // If in macro, expand it first and highlight the expanded code.
105 for event in root.value.preorder_with_tokens() {
106 let event_range = match &event {
107 WalkEvent::Enter(it) | WalkEvent::Leave(it) => it.text_range(),
110 // Element outside of the viewport, no need to highlight
111 if range_to_highlight.intersect(event_range).is_none() {
115 // Track "inside macro" state
116 match event.clone().map(|it| it.into_node().and_then(ast::MacroCall::cast)) {
117 WalkEvent::Enter(Some(mc)) => {
118 if let Some(range) = macro_call_range(&mc) {
121 highlight: HlTag::Symbol(SymbolKind::Macro).into(),
125 current_macro_call = Some(mc.clone());
128 WalkEvent::Leave(Some(mc)) => {
129 assert_eq!(current_macro_call, Some(mc));
130 current_macro_call = None;
135 match event.clone().map(|it| it.into_node().and_then(ast::Macro::cast)) {
136 WalkEvent::Enter(Some(mac)) => {
137 macro_highlighter.init();
138 current_macro = Some(mac);
141 WalkEvent::Leave(Some(mac)) => {
142 assert_eq!(current_macro, Some(mac));
143 current_macro = None;
144 macro_highlighter = MacroHighlighter::default();
149 WalkEvent::Enter(NodeOrToken::Node(node)) if ast::Attr::can_cast(node.kind()) => {
150 inside_attribute = true
152 WalkEvent::Leave(NodeOrToken::Node(node)) if ast::Attr::can_cast(node.kind()) => {
153 inside_attribute = false
158 let element = match event {
159 WalkEvent::Enter(it) => it,
160 WalkEvent::Leave(it) => {
161 if let Some(node) = it.as_node() {
162 inject::doc_comment(hl, sema, root.with_value(node));
168 let range = element.text_range();
170 if current_macro.is_some() {
171 if let Some(tok) = element.as_token() {
172 macro_highlighter.advance(tok);
176 let element_to_highlight = if current_macro_call.is_some() && element.kind() != COMMENT {
177 // Inside a macro -- expand it first
178 let token = match element.clone().into_token() {
179 Some(it) if it.parent().map_or(false, |it| it.kind() == TOKEN_TREE) => it,
182 let token = sema.descend_into_macros(token.clone());
183 match token.parent() {
185 // We only care Name and Name_ref
186 match (token.kind(), parent.kind()) {
187 (IDENT, NAME) | (IDENT, NAME_REF) => parent.into(),
191 None => token.into(),
197 if let Some(token) = element.as_token().cloned().and_then(ast::String::cast) {
199 let expanded = element_to_highlight.as_token().unwrap().clone();
200 if inject::ra_fixture(hl, &sema, token, expanded).is_some() {
206 if let Some(_) = macro_highlighter.highlight(element_to_highlight.clone()) {
210 if let Some((mut highlight, binding_hash)) = highlight::element(
212 &mut bindings_shadow_count,
213 syntactic_name_ref_highlighting,
214 element_to_highlight.clone(),
216 if inside_attribute {
217 highlight = highlight | HlMod::Attribute;
220 hl.add(HlRange { range, highlight, binding_hash });
223 if let Some(string) = element_to_highlight.as_token().cloned().and_then(ast::String::cast) {
224 highlight_format_string(hl, &string, range);
225 // Highlight escape sequences
226 if let Some(char_ranges) = string.char_ranges() {
227 for (piece_range, _) in char_ranges.iter().filter(|(_, char)| char.is_ok()) {
228 if string.text()[piece_range.start().into()..].starts_with('\\') {
230 range: piece_range + range.start(),
231 highlight: HlTag::EscapeSequence.into(),
241 fn macro_call_range(macro_call: &ast::MacroCall) -> Option<TextRange> {
242 let path = macro_call.path()?;
243 let name_ref = path.segment()?.name_ref()?;
245 let range_start = name_ref.syntax().text_range().start();
246 let mut range_end = name_ref.syntax().text_range().end();
247 for sibling in path.syntax().siblings_with_tokens(Direction::Next) {
248 match sibling.kind() {
249 T![!] | IDENT => range_end = sibling.text_range().end(),
254 Some(TextRange::new(range_start, range_end))