16 use hir::{Name, Semantics};
17 use ide_db::{FxHashMap, RootDatabase};
19 ast, AstNode, AstToken, NodeOrToken, SyntaxKind::*, SyntaxNode, TextRange, WalkEvent, T,
23 syntax_highlighting::{
24 escape::highlight_escape_string, format::highlight_format_string, highlights::Highlights,
25 macro_::MacroHighlighter, tags::Highlight,
30 pub(crate) use html::highlight_as_html;
32 #[derive(Debug, Clone, Copy)]
35 pub highlight: Highlight,
36 pub binding_hash: Option<u64>,
39 // Feature: Semantic Syntax Highlighting
41 // rust-analyzer highlights the code semantically.
42 // For example, `Bar` in `foo::Bar` might be colored differently depending on whether `Bar` is an enum or a trait.
43 // rust-analyzer does not specify colors directly, instead it assigns a tag (like `struct`) and a set of modifiers (like `declaration`) to each token.
44 // It's up to the client to map those to specific colors.
46 // The general rule is that a reference to an entity gets colored the same way as the entity itself.
47 // We also give special modifier for `mut` and `&mut` local variables.
52 // Rust-analyzer currently emits the following token tags:
57 // attribute:: Emitted for attribute macros.
58 // enum:: Emitted for enums.
59 // function:: Emitted for free-standing functions.
60 // derive:: Emitted for derive macros.
61 // macro:: Emitted for function-like macros.
62 // method:: Emitted for associated functions, also knowns as methods.
63 // namespace:: Emitted for modules.
64 // struct:: Emitted for structs.
65 // trait:: Emitted for traits.
66 // typeAlias:: Emitted for type aliases and `Self` in `impl`s.
67 // union:: Emitted for unions.
72 // boolean:: Emitted for the boolean literals `true` and `false`.
73 // character:: Emitted for character literals.
74 // number:: Emitted for numeric literals.
75 // string:: Emitted for string literals.
76 // escapeSequence:: Emitted for escaped sequences inside strings like `\n`.
77 // formatSpecifier:: Emitted for format specifiers `{:?}` in `format!`-like macros.
82 // operator:: Emitted for general operators.
83 // arithmetic:: Emitted for the arithmetic operators `+`, `-`, `*`, `/`, `+=`, `-=`, `*=`, `/=`.
84 // bitwise:: Emitted for the bitwise operators `|`, `&`, `!`, `^`, `|=`, `&=`, `^=`.
85 // comparison:: Emitted for the comparison operators `>`, `<`, `==`, `>=`, `<=`, `!=`.
86 // logical:: Emitted for the logical operators `||`, `&&`, `!`.
91 // punctuation:: Emitted for general punctuation.
92 // attributeBracket:: Emitted for attribute invocation brackets, that is the `#[` and `]` tokens.
93 // angle:: Emitted for `<>` angle brackets.
94 // brace:: Emitted for `{}` braces.
95 // bracket:: Emitted for `[]` brackets.
96 // parenthesis:: Emitted for `()` parentheses.
97 // colon:: Emitted for the `:` token.
98 // comma:: Emitted for the `,` token.
99 // dot:: Emitted for the `.` token.
100 // semi:: Emitted for the `;` token.
101 // macroBang:: Emitted for the `!` token in macro calls.
106 // builtinAttribute:: Emitted for names to builtin attributes in attribute path, the `repr` in `#[repr(u8)]` for example.
107 // builtinType:: Emitted for builtin types like `u32`, `str` and `f32`.
108 // comment:: Emitted for comments.
109 // constParameter:: Emitted for const parameters.
110 // deriveHelper:: Emitted for derive helper attributes.
111 // enumMember:: Emitted for enum variants.
112 // generic:: Emitted for generic tokens that have no mapping.
113 // keyword:: Emitted for keywords.
114 // label:: Emitted for labels.
115 // lifetime:: Emitted for lifetimes.
116 // parameter:: Emitted for non-self function parameters.
117 // property:: Emitted for struct and union fields.
118 // selfKeyword:: Emitted for the self function parameter and self path-specifier.
119 // selfTypeKeyword:: Emitted for the Self type parameter.
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());
182 let krate = match sema.scope(&root) {
183 Some(it) => it.krate(),
184 None => return hl.to_vec(),
193 syntactic_name_ref_highlighting,
200 sema: &Semantics<'_, RootDatabase>,
204 range_to_highlight: TextRange,
205 syntactic_name_ref_highlighting: bool,
207 let is_unlinked = sema.to_module_def(file_id).is_none();
208 let mut bindings_shadow_count: FxHashMap<Name, u32> = FxHashMap::default();
216 fn item(&self) -> &ast::Item {
218 AttrOrDerive::Attr(item) | AttrOrDerive::Derive(item) => item,
223 let mut tt_level = 0;
224 let mut attr_or_derive_item = None;
225 let mut current_macro: Option<ast::Macro> = None;
226 let mut macro_highlighter = MacroHighlighter::default();
227 let mut inside_attribute = false;
229 // Walk all nodes, keeping track of whether we are inside a macro or not.
230 // If in macro, expand it first and highlight the expanded code.
231 for event in root.preorder_with_tokens() {
232 use WalkEvent::{Enter, Leave};
234 let range = match &event {
235 Enter(it) | Leave(it) => it.text_range(),
238 // Element outside of the viewport, no need to highlight
239 if range_to_highlight.intersect(range).is_none() {
243 // set macro and attribute highlighting states
244 match event.clone() {
245 Enter(NodeOrToken::Node(node)) if ast::TokenTree::can_cast(node.kind()) => {
248 Leave(NodeOrToken::Node(node)) if ast::TokenTree::can_cast(node.kind()) => {
251 Enter(NodeOrToken::Node(node)) if ast::Attr::can_cast(node.kind()) => {
252 inside_attribute = true
254 Leave(NodeOrToken::Node(node)) if ast::Attr::can_cast(node.kind()) => {
255 inside_attribute = false
258 Enter(NodeOrToken::Node(node)) if ast::Item::can_cast(node.kind()) => {
259 match ast::Item::cast(node.clone()) {
260 Some(ast::Item::MacroRules(mac)) => {
261 macro_highlighter.init();
262 current_macro = Some(mac.into());
265 Some(ast::Item::MacroDef(mac)) => {
266 macro_highlighter.init();
267 current_macro = Some(mac.into());
271 if matches!(node.kind(), FN | CONST | STATIC) {
272 bindings_shadow_count.clear();
275 if attr_or_derive_item.is_none() {
276 if sema.is_attr_macro_call(&item) {
277 attr_or_derive_item = Some(AttrOrDerive::Attr(item));
279 let adt = match item {
280 ast::Item::Enum(it) => Some(ast::Adt::Enum(it)),
281 ast::Item::Struct(it) => Some(ast::Adt::Struct(it)),
282 ast::Item::Union(it) => Some(ast::Adt::Union(it)),
286 Some(adt) if sema.is_derive_annotated(&adt) => {
287 attr_or_derive_item =
288 Some(AttrOrDerive::Derive(ast::Item::from(adt)));
298 Leave(NodeOrToken::Node(node)) if ast::Item::can_cast(node.kind()) => {
299 match ast::Item::cast(node.clone()) {
300 Some(ast::Item::MacroRules(mac)) => {
301 assert_eq!(current_macro, Some(mac.into()));
302 current_macro = None;
303 macro_highlighter = MacroHighlighter::default();
305 Some(ast::Item::MacroDef(mac)) => {
306 assert_eq!(current_macro, Some(mac.into()));
307 current_macro = None;
308 macro_highlighter = MacroHighlighter::default();
311 if attr_or_derive_item.as_ref().map_or(false, |it| *it.item() == item) =>
313 attr_or_derive_item = None;
321 let element = match event {
322 Enter(NodeOrToken::Token(tok)) if tok.kind() == WHITESPACE => continue,
324 Leave(NodeOrToken::Token(_)) => continue,
325 Leave(NodeOrToken::Node(node)) => {
326 // Doc comment highlighting injection, we do this when leaving the node
327 // so that we overwrite the highlighting of the doc comment itself.
328 inject::doc_comment(hl, sema, file_id, &node);
333 if current_macro.is_some() {
334 if let Some(tok) = element.as_token() {
335 macro_highlighter.advance(tok);
339 let element = match element.clone() {
340 NodeOrToken::Node(n) => match ast::NameLike::cast(n) {
341 Some(n) => NodeOrToken::Node(n),
344 NodeOrToken::Token(t) => NodeOrToken::Token(t),
346 let token = element.as_token().cloned();
348 // Descending tokens into macros is expensive even if no descending occurs, so make sure
349 // that we actually are in a position where descending is possible.
350 let in_macro = tt_level > 0
351 || match attr_or_derive_item {
352 Some(AttrOrDerive::Attr(_)) => true,
353 Some(AttrOrDerive::Derive(_)) => inside_attribute,
356 let descended_element = if in_macro {
357 // Attempt to descend tokens into macro-calls.
359 NodeOrToken::Token(token) if token.kind() != COMMENT => {
360 let token = match attr_or_derive_item {
361 Some(AttrOrDerive::Attr(_)) => {
362 sema.descend_into_macros_with_kind_preference(token)
364 Some(AttrOrDerive::Derive(_)) | None => {
365 sema.descend_into_macros_single(token)
368 match token.parent().and_then(ast::NameLike::cast) {
369 // Remap the token into the wrapping single token nodes
370 Some(parent) => match (token.kind(), parent.syntax().kind()) {
371 (T![self] | T![ident], NAME | NAME_REF) => NodeOrToken::Node(parent),
372 (T![self] | T![super] | T![crate] | T![Self], NAME_REF) => {
373 NodeOrToken::Node(parent)
375 (INT_NUMBER, NAME_REF) => NodeOrToken::Node(parent),
376 (LIFETIME_IDENT, LIFETIME) => NodeOrToken::Node(parent),
377 _ => NodeOrToken::Token(token),
379 None => NodeOrToken::Token(token),
388 // FIXME: do proper macro def highlighting https://github.com/rust-lang/rust-analyzer/issues/6232
389 // Skip metavariables from being highlighted to prevent keyword highlighting in them
390 if descended_element.as_token().and_then(|t| macro_highlighter.highlight(t)).is_some() {
394 // string highlight injections, note this does not use the descended element as proc-macros
395 // can rewrite string literals which invalidates our indices
396 if let (Some(token), Some(descended_token)) = (token, descended_element.as_token()) {
397 if ast::String::can_cast(token.kind()) && ast::String::can_cast(descended_token.kind())
399 let string = ast::String::cast(token);
400 let string_to_highlight = ast::String::cast(descended_token.clone());
401 if let Some((string, expanded_string)) = string.zip(string_to_highlight) {
403 if inject::ra_fixture(hl, sema, &string, &expanded_string).is_some() {
407 highlight_format_string(hl, &string, &expanded_string, range);
408 highlight_escape_string(hl, &string, range.start());
410 } else if ast::ByteString::can_cast(token.kind())
411 && ast::ByteString::can_cast(descended_token.kind())
413 if let Some(byte_string) = ast::ByteString::cast(token) {
414 highlight_escape_string(hl, &byte_string, range.start());
419 let element = match descended_element {
420 NodeOrToken::Node(name_like) => highlight::name_like(
423 &mut bindings_shadow_count,
424 syntactic_name_ref_highlighting,
427 NodeOrToken::Token(token) => highlight::token(sema, token).zip(Some(None)),
429 if let Some((mut highlight, binding_hash)) = element {
430 if is_unlinked && highlight.tag == HlTag::UnresolvedReference {
431 // do not emit unresolved references if the file is unlinked
432 // let the editor do its highlighting for these tokens instead
435 if highlight.tag == HlTag::UnresolvedReference
436 && matches!(attr_or_derive_item, Some(AttrOrDerive::Derive(_)) if inside_attribute)
438 // do not emit unresolved references in derive helpers if the token mapping maps to
439 // something unresolvable. FIXME: There should be a way to prevent that
442 if inside_attribute {
443 highlight |= HlMod::Attribute
446 hl.add(HlRange { range, highlight, binding_hash });