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.
54 // Token modifiers allow to style some elements in the source code more precisely.
56 // Rust-analyzer currently emits the following token modifiers:
59 // associated:: Emitted for associated items.
60 // async:: Emitted for async functions and the `async` and `await` keywords.
61 // attribute:: Emitted for tokens inside attributes.
62 // callable:: Emitted for locals whose types implements one of the `Fn*` traits.
63 // consuming:: Emitted for locals that are being consumed when use in a function call.
64 // controlFlow:: Emitted for control-flow related tokens, this includes the `?` operator.
65 // declaration:: Emitted for names of definitions, like `foo` in `fn foo() {}`.
66 // documentation:: Emitted for documentation comments.
67 // injected:: Emitted for doc-string injected highlighting like rust source blocks in documentation.
68 // intraDocLink:: Emitted for intra doc links in doc-strings.
69 // library:: Emitted for items that are defined outside of the current crate.
70 // mutable:: Emitted for mutable locals and statics.
71 // static:: Emitted for "static" functions, also known as functions that do not take a `self` param.
72 // trait:: Emitted for associated trait items.
73 // unsafe:: Emitted for unsafe operations, like unsafe function calls, as well as the `unsafe` token.
76 // image::https://user-images.githubusercontent.com/48062697/113164457-06cfb980-9239-11eb-819b-0f93e646acf8.png[]
77 // image::https://user-images.githubusercontent.com/48062697/113187625-f7f50100-9250-11eb-825e-91c58f236071.png[]
78 pub(crate) fn highlight(
81 range_to_highlight: Option<TextRange>,
82 syntactic_name_ref_highlighting: bool,
84 let _p = profile::span("highlight");
85 let sema = Semantics::new(db);
87 // Determine the root based on the given range.
88 let (root, range_to_highlight) = {
89 let source_file = sema.parse(file_id);
90 match range_to_highlight {
92 let node = match source_file.syntax().covering_element(range) {
93 NodeOrToken::Node(it) => it,
94 NodeOrToken::Token(it) => it.parent().unwrap(),
98 None => (source_file.syntax().clone(), source_file.syntax().text_range()),
102 let mut hl = highlights::Highlights::new(root.text_range());
106 InFile::new(file_id.into(), &root),
107 sema.scope(&root).krate(),
109 syntactic_name_ref_highlighting,
116 sema: &Semantics<RootDatabase>,
117 root: InFile<&SyntaxNode>,
118 krate: Option<hir::Crate>,
119 range_to_highlight: TextRange,
120 syntactic_name_ref_highlighting: bool,
122 let mut bindings_shadow_count: FxHashMap<Name, u32> = FxHashMap::default();
124 let mut current_macro_call: Option<ast::MacroCall> = None;
125 let mut current_macro: Option<ast::Macro> = None;
126 let mut macro_highlighter = MacroHighlighter::default();
127 let mut inside_attribute = false;
129 // Walk all nodes, keeping track of whether we are inside a macro or not.
130 // If in macro, expand it first and highlight the expanded code.
131 for event in root.value.preorder_with_tokens() {
132 let event_range = match &event {
133 WalkEvent::Enter(it) | WalkEvent::Leave(it) => it.text_range(),
136 // Element outside of the viewport, no need to highlight
137 if range_to_highlight.intersect(event_range).is_none() {
141 // Track "inside macro" state
142 match event.clone().map(|it| it.into_node().and_then(ast::MacroCall::cast)) {
143 WalkEvent::Enter(Some(mc)) => {
144 if let Some(range) = macro_call_range(&mc) {
147 highlight: HlTag::Symbol(SymbolKind::Macro).into(),
151 current_macro_call = Some(mc.clone());
154 WalkEvent::Leave(Some(mc)) => {
155 assert_eq!(current_macro_call, Some(mc));
156 current_macro_call = None;
161 match event.clone().map(|it| it.into_node().and_then(ast::Macro::cast)) {
162 WalkEvent::Enter(Some(mac)) => {
163 macro_highlighter.init();
164 current_macro = Some(mac);
167 WalkEvent::Leave(Some(mac)) => {
168 assert_eq!(current_macro, Some(mac));
169 current_macro = None;
170 macro_highlighter = MacroHighlighter::default();
175 WalkEvent::Enter(NodeOrToken::Node(node)) if ast::Attr::can_cast(node.kind()) => {
176 inside_attribute = true
178 WalkEvent::Leave(NodeOrToken::Node(node)) if ast::Attr::can_cast(node.kind()) => {
179 inside_attribute = false
184 let element = match event {
185 WalkEvent::Enter(it) => it,
186 WalkEvent::Leave(it) => {
187 if let Some(node) = it.as_node() {
188 inject::doc_comment(hl, sema, root.with_value(node));
194 let range = element.text_range();
196 if current_macro.is_some() {
197 if let Some(tok) = element.as_token() {
198 macro_highlighter.advance(tok);
202 let element_to_highlight = if current_macro_call.is_some() && element.kind() != COMMENT {
203 // Inside a macro -- expand it first
204 let token = match element.clone().into_token() {
205 Some(it) if it.parent().map_or(false, |it| it.kind() == TOKEN_TREE) => it,
208 let token = sema.descend_into_macros(token.clone());
209 match token.parent() {
211 // We only care Name and Name_ref
212 match (token.kind(), parent.kind()) {
213 (IDENT, NAME) | (IDENT, NAME_REF) => parent.into(),
217 None => token.into(),
223 if let Some(token) = element.as_token().cloned().and_then(ast::String::cast) {
225 let expanded = element_to_highlight.as_token().unwrap().clone();
226 if inject::ra_fixture(hl, &sema, token, expanded).is_some() {
232 if let Some(_) = macro_highlighter.highlight(element_to_highlight.clone()) {
236 if let Some((mut highlight, binding_hash)) = highlight::element(
239 &mut bindings_shadow_count,
240 syntactic_name_ref_highlighting,
241 element_to_highlight.clone(),
243 if inside_attribute {
244 highlight = highlight | HlMod::Attribute;
247 hl.add(HlRange { range, highlight, binding_hash });
250 if let Some(string) = element_to_highlight.as_token().cloned().and_then(ast::String::cast) {
251 highlight_format_string(hl, &string, range);
252 // Highlight escape sequences
253 if let Some(char_ranges) = string.char_ranges() {
254 for (piece_range, _) in char_ranges.iter().filter(|(_, char)| char.is_ok()) {
255 if string.text()[piece_range.start().into()..].starts_with('\\') {
257 range: piece_range + range.start(),
258 highlight: HlTag::EscapeSequence.into(),
268 fn macro_call_range(macro_call: &ast::MacroCall) -> Option<TextRange> {
269 let path = macro_call.path()?;
270 let name_ref = path.segment()?.name_ref()?;
272 let range_start = name_ref.syntax().text_range().start();
273 let mut range_end = name_ref.syntax().text_range().end();
274 for sibling in path.syntax().siblings_with_tokens(Direction::Next) {
275 match sibling.kind() {
276 T![!] | IDENT => range_end = sibling.text_range().end(),
281 Some(TextRange::new(range_start, range_end))