15 use hir::{InFile, Name, Semantics};
16 use ide_db::{RootDatabase, SymbolKind};
17 use rustc_hash::FxHashMap;
19 ast::{self, HasFormatSpecifier},
20 match_ast, 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 a 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.
55 // Rust-analyzer currently emits the following token tags:
60 // attribute:: Emitted for attribute macros.
61 // enum:: Emitted for enums.
62 // function:: Emitted for free-standing functions.
63 // derive:: Emitted for derive macros.
64 // macro:: Emitted for function-like macros.
65 // method:: Emitted for associated functions, also knowns as methods.
66 // namespace:: Emitted for modules.
67 // struct:: Emitted for structs.
68 // trait:: Emitted for traits.
69 // typeAlias:: Emitted for type aliases and `Self` in `impl`s.
70 // union:: Emitted for unions.
75 // boolean:: Emitted for the boolean literals `true` and `false`.
76 // character:: Emitted for character literals.
77 // number:: Emitted for numeric literals.
78 // string:: Emitted for string literals.
79 // escapeSequence:: Emitted for escaped sequences inside strings like `\n`.
80 // formatSpecifier:: Emitted for format specifiers `{:?}` in `format!`-like macros.
85 // operator:: Emitted for general operators.
86 // arithmetic:: Emitted for the arithmetic operators `+`, `-`, `*`, `/`, `+=`, `-=`, `*=`, `/=`.
87 // bitwise:: Emitted for the bitwise operators `|`, `&`, `!`, `^`, `|=`, `&=`, `^=`.
88 // comparison:: Emitted for the comparison operators `>`, `<`, `==`, `>=`, `<=`, `!=`.
89 // logical:: Emitted for the logical operators `||`, `&&`, `!`.
94 // punctuation:: Emitted for general punctuation.
95 // attributeBracket:: Emitted for attribute invocation brackets, that is the `#[` and `]` tokens.
96 // angle:: Emitted for `<>` angle brackets.
97 // brace:: Emitted for `{}` braces.
98 // bracket:: Emitted for `[]` brackets.
99 // parenthesis:: Emitted for `()` parentheses.
100 // colon:: Emitted for the `:` token.
101 // comma:: Emitted for the `,` token.
102 // dot:: Emitted for the `.` token.
103 // Semi:: Emitted for the `;` token.
108 // builtinAttribute:: Emitted for names to builtin attributes in attribute path, the `repr` in `#[repr(u8)]` for example.
109 // builtinType:: Emitted for builtin types like `u32`, `str` and `f32`.
110 // comment:: Emitted for comments.
111 // constParameter:: Emitted for const parameters.
112 // enumMember:: Emitted for enum variants.
113 // generic:: Emitted for generic tokens that have no mapping.
114 // keyword:: Emitted for keywords.
115 // label:: Emitted for labels.
116 // lifetime:: Emitted for lifetimes.
117 // parameter:: Emitted for non-self function parameters.
118 // property:: Emitted for struct and union fields.
119 // selfKeyword:: Emitted for the self function parameter and self path-specifier.
120 // toolModule:: Emitted for tool modules.
121 // typeParameter:: Emitted for type parameters.
122 // unresolvedReference:: Emitted for unresolved references, names that rust-analyzer can't find the definition of.
123 // variable:: Emitted for locals, constants and statics.
128 // Token modifiers allow to style some elements in the source code more precisely.
130 // Rust-analyzer currently emits the following token modifiers:
133 // async:: Emitted for async functions and the `async` and `await` keywords.
134 // attribute:: Emitted for tokens inside attributes.
135 // callable:: Emitted for locals whose types implements one of the `Fn*` traits.
136 // constant:: Emitted for consts.
137 // consuming:: Emitted for locals that are being consumed when use in a function call.
138 // controlFlow:: Emitted for control-flow related tokens, this includes the `?` operator.
139 // crateRoot:: Emitted for crate names, like `serde` and `crate`.
140 // declaration:: Emitted for names of definitions, like `foo` in `fn foo() {}`.
141 // defaultLibrary:: Emitted for items from built-in crates (std, core, alloc, test and proc_macro).
142 // documentation:: Emitted for documentation comments.
143 // injected:: Emitted for doc-string injected highlighting like rust source blocks in documentation.
144 // intraDocLink:: Emitted for intra doc links in doc-strings.
145 // library:: Emitted for items that are defined outside of the current crate.
146 // mutable:: Emitted for mutable locals and statics as well as functions taking `&mut self`.
147 // public:: Emitted for items that are from the current crate and are `pub`.
148 // reference:: Emitted for locals behind a reference and functions taking `self` by reference.
149 // static:: Emitted for "static" functions, also known as functions that do not take a `self` param, as well as statics and consts.
150 // trait:: Emitted for associated trait items.
151 // unsafe:: Emitted for unsafe operations, like unsafe function calls, as well as the `unsafe` token.
154 // image::https://user-images.githubusercontent.com/48062697/113164457-06cfb980-9239-11eb-819b-0f93e646acf8.png[]
155 // image::https://user-images.githubusercontent.com/48062697/113187625-f7f50100-9250-11eb-825e-91c58f236071.png[]
156 pub(crate) fn highlight(
159 range_to_highlight: Option<TextRange>,
160 syntactic_name_ref_highlighting: bool,
162 let _p = profile::span("highlight");
163 let sema = Semantics::new(db);
165 // Determine the root based on the given range.
166 let (root, range_to_highlight) = {
167 let source_file = sema.parse(file_id);
168 let source_file = source_file.syntax();
169 match range_to_highlight {
171 let node = match source_file.covering_element(range) {
172 NodeOrToken::Node(it) => it,
173 NodeOrToken::Token(it) => it.parent().unwrap_or_else(|| source_file.clone()),
177 None => (source_file.clone(), source_file.text_range()),
181 let mut hl = highlights::Highlights::new(root.text_range());
185 InFile::new(file_id.into(), &root),
186 sema.scope(&root).krate(),
188 syntactic_name_ref_highlighting,
195 sema: &Semantics<RootDatabase>,
196 root: InFile<&SyntaxNode>,
197 krate: Option<hir::Crate>,
198 range_to_highlight: TextRange,
199 syntactic_name_ref_highlighting: bool,
201 let mut bindings_shadow_count: FxHashMap<Name, u32> = FxHashMap::default();
203 let mut current_macro_call: Option<ast::MacroCall> = None;
204 let mut current_attr_call = None;
205 let mut current_macro: Option<ast::Macro> = None;
206 let mut macro_highlighter = MacroHighlighter::default();
207 let mut inside_attribute = false;
209 // Walk all nodes, keeping track of whether we are inside a macro or not.
210 // If in macro, expand it first and highlight the expanded code.
211 for event in root.value.preorder_with_tokens() {
212 let event_range = match &event {
213 WalkEvent::Enter(it) | WalkEvent::Leave(it) => it.text_range(),
216 // Element outside of the viewport, no need to highlight
217 if range_to_highlight.intersect(event_range).is_none() {
221 match event.clone() {
222 WalkEvent::Enter(NodeOrToken::Node(node)) => {
225 ast::MacroCall(mcall) => {
226 if let Some(range) = macro_call_range(&mcall) {
229 highlight: HlTag::Symbol(SymbolKind::Macro).into(),
233 current_macro_call = Some(mcall);
237 macro_highlighter.init();
238 current_macro = Some(mac);
242 if sema.is_attr_macro_call(&item) {
243 current_attr_call = Some(item);
246 ast::Attr(__) => inside_attribute = true,
251 WalkEvent::Leave(NodeOrToken::Node(node)) => {
254 ast::MacroCall(mcall) => {
255 assert_eq!(current_macro_call, Some(mcall));
256 current_macro_call = None;
259 assert_eq!(current_macro, Some(mac));
260 current_macro = None;
261 macro_highlighter = MacroHighlighter::default();
264 if current_attr_call == Some(item) {
265 current_attr_call = None;
268 ast::Attr(__) => inside_attribute = false,
276 let element = match event {
277 WalkEvent::Enter(it) => it,
278 WalkEvent::Leave(it) => {
279 if let Some(node) = it.as_node() {
280 inject::doc_comment(hl, sema, root.with_value(node));
286 let range = element.text_range();
288 if current_macro.is_some() {
289 if let Some(tok) = element.as_token() {
290 macro_highlighter.advance(tok);
294 let descend_token = (current_macro_call.is_some() || current_attr_call.is_some())
295 && element.kind() != COMMENT;
296 let element_to_highlight = if descend_token {
297 // Inside a macro -- expand it first
298 let token = match element.clone().into_token() {
299 Some(it) if current_macro_call.is_some() => {
300 let not_in_tt = it.parent().map_or(true, |it| it.kind() != TOKEN_TREE);
309 let token = sema.descend_into_macros_single(token);
310 match token.parent() {
312 // We only care Name and Name_ref
313 match (token.kind(), parent.kind()) {
314 (T![ident], NAME | NAME_REF) => parent.into(),
315 (T![self] | T![super] | T![crate], NAME_REF) => parent.into(),
316 (INT_NUMBER, NAME_REF) => parent.into(),
320 None => token.into(),
326 if macro_highlighter.highlight(element_to_highlight.clone()).is_some() {
330 if let (Some(token), Some(token_to_highlight)) =
331 (element.into_token(), element_to_highlight.as_token())
333 let string = ast::String::cast(token);
334 let string_to_highlight = ast::String::cast(token_to_highlight.clone());
335 if let Some((string, expanded_string)) = string.zip(string_to_highlight) {
337 if inject::ra_fixture(hl, sema, &string, &expanded_string).is_some() {
341 highlight_format_string(hl, &string, &expanded_string, range);
342 // Highlight escape sequences
343 if let Some(char_ranges) = string.char_ranges() {
344 for (piece_range, _) in char_ranges.iter().filter(|(_, char)| char.is_ok()) {
345 if string.text()[piece_range.start().into()..].starts_with('\\') {
347 range: piece_range + range.start(),
348 highlight: HlTag::EscapeSequence.into(),
357 if let Some((mut highlight, binding_hash)) = highlight::element(
360 &mut bindings_shadow_count,
361 syntactic_name_ref_highlighting,
362 element_to_highlight.clone(),
364 if inside_attribute {
365 highlight |= HlMod::Attribute
368 hl.add(HlRange { range, highlight, binding_hash });
373 fn macro_call_range(macro_call: &ast::MacroCall) -> Option<TextRange> {
374 let path = macro_call.path()?;
375 let name_ref = path.segment()?.name_ref()?;
377 let range_start = name_ref.syntax().text_range().start();
378 let mut range_end = name_ref.syntax().text_range().end();
379 for sibling in path.syntax().siblings_with_tokens(Direction::Next) {
380 if let T![!] | T![ident] = sibling.kind() {
381 range_end = sibling.text_range().end();
385 Some(TextRange::new(range_start, range_end))