1 //! Implements syntax highlighting.
8 use hir::{Name, Semantics};
10 defs::{classify_name, classify_name_ref, Definition, NameClass, NameRefClass},
15 ast::{self, HasFormatSpecifier, HasQuotes, HasStringValue},
16 AstNode, AstToken, Direction, NodeOrToken, SyntaxElement,
18 SyntaxToken, TextRange, WalkEvent, T,
20 use rustc_hash::FxHashMap;
22 use crate::{call_info::ActiveParameter, Analysis, FileId};
24 use ast::FormatSpecifier;
25 pub(crate) use html::highlight_as_html;
26 pub use tags::{Highlight, HighlightModifier, HighlightModifiers, HighlightTag};
28 #[derive(Debug, Clone)]
29 pub struct HighlightedRange {
31 pub highlight: Highlight,
32 pub binding_hash: Option<u64>,
36 struct HighlightedRangeStack {
37 stack: Vec<Vec<HighlightedRange>>,
40 /// We use a stack to implement the flattening logic for the highlighted
42 impl HighlightedRangeStack {
44 Self { stack: vec![Vec::new()] }
48 self.stack.push(Vec::new());
51 /// Flattens the highlighted ranges.
53 /// For example `#[cfg(feature = "foo")]` contains the nested ranges:
54 /// 1) parent-range: Attribute [0, 23)
55 /// 2) child-range: String [16, 21)
57 /// The following code implements the flattening, for our example this results to:
58 /// `[Attribute [0, 16), String [16, 21), Attribute [21, 23)]`
60 let children = self.stack.pop().unwrap();
61 let prev = self.stack.last_mut().unwrap();
62 let needs_flattening = !children.is_empty()
64 && prev.last().unwrap().range.contains_range(children.first().unwrap().range);
65 if !needs_flattening {
66 prev.extend(children);
68 let mut parent = prev.pop().unwrap();
70 assert!(parent.range.contains_range(ele.range));
71 let mut cloned = parent.clone();
72 parent.range = TextRange::new(parent.range.start(), ele.range.start());
73 cloned.range = TextRange::new(ele.range.end(), cloned.range.end());
74 if !parent.range.is_empty() {
80 if !parent.range.is_empty() {
86 fn add(&mut self, range: HighlightedRange) {
89 .expect("during DFS traversal, the stack must not be empty")
93 fn flattened(mut self) -> Vec<HighlightedRange> {
97 "after DFS traversal, the stack should only contain a single element"
99 let mut res = self.stack.pop().unwrap();
100 res.sort_by_key(|range| range.range.start());
101 // Check that ranges are sorted and disjoint
104 .zip(res.iter().skip(1))
105 .all(|(left, right)| left.range.end() <= right.range.start()));
110 pub(crate) fn highlight(
113 range_to_highlight: Option<TextRange>,
114 ) -> Vec<HighlightedRange> {
115 let _p = profile("highlight");
116 let sema = Semantics::new(db);
118 // Determine the root based on the given range.
119 let (root, range_to_highlight) = {
120 let source_file = sema.parse(file_id);
121 match range_to_highlight {
123 let node = match source_file.syntax().covering_element(range) {
124 NodeOrToken::Node(it) => it,
125 NodeOrToken::Token(it) => it.parent(),
129 None => (source_file.syntax().clone(), source_file.syntax().text_range()),
133 let mut bindings_shadow_count: FxHashMap<Name, u32> = FxHashMap::default();
134 // We use a stack for the DFS traversal below.
135 // When we leave a node, the we use it to flatten the highlighted ranges.
136 let mut stack = HighlightedRangeStack::new();
138 let mut current_macro_call: Option<ast::MacroCall> = None;
139 let mut format_string: Option<SyntaxElement> = None;
141 // Walk all nodes, keeping track of whether we are inside a macro or not.
142 // If in macro, expand it first and highlight the expanded code.
143 for event in root.preorder_with_tokens() {
145 WalkEvent::Enter(_) => stack.push(),
146 WalkEvent::Leave(_) => stack.pop(),
149 let event_range = match &event {
150 WalkEvent::Enter(it) => it.text_range(),
151 WalkEvent::Leave(it) => it.text_range(),
154 // Element outside of the viewport, no need to highlight
155 if range_to_highlight.intersect(event_range).is_none() {
159 // Track "inside macro" state
160 match event.clone().map(|it| it.into_node().and_then(ast::MacroCall::cast)) {
161 WalkEvent::Enter(Some(mc)) => {
162 current_macro_call = Some(mc.clone());
163 if let Some(range) = macro_call_range(&mc) {
164 stack.add(HighlightedRange {
166 highlight: HighlightTag::Macro.into(),
170 if let Some(name) = mc.is_macro_rules() {
171 if let Some((highlight, binding_hash)) = highlight_element(
173 &mut bindings_shadow_count,
174 name.syntax().clone().into(),
176 stack.add(HighlightedRange {
177 range: name.syntax().text_range(),
185 WalkEvent::Leave(Some(mc)) => {
186 assert!(current_macro_call == Some(mc));
187 current_macro_call = None;
188 format_string = None;
194 let element = match event {
195 WalkEvent::Enter(it) => it,
196 WalkEvent::Leave(_) => continue,
199 let range = element.text_range();
201 let element_to_highlight = if current_macro_call.is_some() {
202 // Inside a macro -- expand it first
203 let token = match element.clone().into_token() {
204 Some(it) if it.parent().kind() == TOKEN_TREE => it,
207 let token = sema.descend_into_macros(token.clone());
208 let parent = token.parent();
210 // Check if macro takes a format string and remember it for highlighting later.
211 // The macros that accept a format string expand to a compiler builtin macros
212 // `format_args` and `format_args_nl`.
213 if let Some(fmt_macro_call) = parent.parent().and_then(ast::MacroCall::cast) {
215 fmt_macro_call.path().and_then(|p| p.segment()).and_then(|s| s.name_ref())
217 match name.text().as_str() {
218 "format_args" | "format_args_nl" => {
219 format_string = parent
220 .children_with_tokens()
221 .filter(|t| t.kind() != WHITESPACE)
224 ast::String::can_cast(e.kind())
225 || ast::RawString::can_cast(e.kind())
233 // We only care Name and Name_ref
234 match (token.kind(), parent.kind()) {
235 (IDENT, NAME) | (IDENT, NAME_REF) => parent.into(),
242 if let Some(token) = element.as_token().cloned().and_then(ast::RawString::cast) {
243 let expanded = element_to_highlight.as_token().unwrap().clone();
244 if highlight_injection(&mut stack, &sema, token, expanded).is_some() {
249 let is_format_string = format_string.as_ref() == Some(&element_to_highlight);
251 if let Some((highlight, binding_hash)) =
252 highlight_element(&sema, &mut bindings_shadow_count, element_to_highlight.clone())
254 stack.add(HighlightedRange { range, highlight, binding_hash });
255 if let Some(string) =
256 element_to_highlight.as_token().cloned().and_then(ast::String::cast)
259 if is_format_string {
260 string.lex_format_specifier(|piece_range, kind| {
261 if let Some(highlight) = highlight_format_specifier(kind) {
262 stack.add(HighlightedRange {
263 range: piece_range + range.start(),
264 highlight: highlight.into(),
271 } else if let Some(string) =
272 element_to_highlight.as_token().cloned().and_then(ast::RawString::cast)
275 if is_format_string {
276 string.lex_format_specifier(|piece_range, kind| {
277 if let Some(highlight) = highlight_format_specifier(kind) {
278 stack.add(HighlightedRange {
279 range: piece_range + range.start(),
280 highlight: highlight.into(),
294 fn highlight_format_specifier(kind: FormatSpecifier) -> Option<HighlightTag> {
296 FormatSpecifier::Open
297 | FormatSpecifier::Close
298 | FormatSpecifier::Colon
299 | FormatSpecifier::Fill
300 | FormatSpecifier::Align
301 | FormatSpecifier::Sign
302 | FormatSpecifier::NumberSign
303 | FormatSpecifier::DollarSign
304 | FormatSpecifier::Dot
305 | FormatSpecifier::Asterisk
306 | FormatSpecifier::QuestionMark => HighlightTag::FormatSpecifier,
307 FormatSpecifier::Integer | FormatSpecifier::Zero => HighlightTag::NumericLiteral,
308 FormatSpecifier::Identifier => HighlightTag::Local,
312 fn macro_call_range(macro_call: &ast::MacroCall) -> Option<TextRange> {
313 let path = macro_call.path()?;
314 let name_ref = path.segment()?.name_ref()?;
316 let range_start = name_ref.syntax().text_range().start();
317 let mut range_end = name_ref.syntax().text_range().end();
318 for sibling in path.syntax().siblings_with_tokens(Direction::Next) {
319 match sibling.kind() {
320 T![!] | IDENT => range_end = sibling.text_range().end(),
325 Some(TextRange::new(range_start, range_end))
328 fn highlight_element(
329 sema: &Semantics<RootDatabase>,
330 bindings_shadow_count: &mut FxHashMap<Name, u32>,
331 element: SyntaxElement,
332 ) -> Option<(Highlight, Option<u64>)> {
334 let mut binding_hash = None;
335 let highlight: Highlight = match element.kind() {
337 bindings_shadow_count.clear();
341 // Highlight definitions depending on the "type" of the definition.
343 let name = element.into_node().and_then(ast::Name::cast).unwrap();
344 let name_kind = classify_name(sema, &name);
346 if let Some(NameClass::Definition(Definition::Local(local))) = &name_kind {
347 if let Some(name) = local.name(db) {
348 let shadow_count = bindings_shadow_count.entry(name.clone()).or_default();
350 binding_hash = Some(calc_binding_hash(&name, *shadow_count))
355 Some(NameClass::Definition(def)) => {
356 highlight_name(db, def) | HighlightModifier::Definition
358 Some(NameClass::ConstReference(def)) => highlight_name(db, def),
359 None => highlight_name_by_syntax(name) | HighlightModifier::Definition,
363 // Highlight references like the definitions they resolve to
364 NAME_REF if element.ancestors().any(|it| it.kind() == ATTR) => {
365 Highlight::from(HighlightTag::Function) | HighlightModifier::Attribute
368 let name_ref = element.into_node().and_then(ast::NameRef::cast).unwrap();
369 match classify_name_ref(sema, &name_ref) {
370 Some(name_kind) => match name_kind {
371 NameRefClass::Definition(def) => {
372 if let Definition::Local(local) = &def {
373 if let Some(name) = local.name(db) {
375 bindings_shadow_count.entry(name.clone()).or_default();
376 binding_hash = Some(calc_binding_hash(&name, *shadow_count))
379 highlight_name(db, def)
381 NameRefClass::FieldShorthand { .. } => HighlightTag::Field.into(),
383 None => HighlightTag::UnresolvedReference.into(),
387 // Simple token-based highlighting
388 COMMENT => HighlightTag::Comment.into(),
389 STRING | RAW_STRING | RAW_BYTE_STRING | BYTE_STRING => HighlightTag::StringLiteral.into(),
390 ATTR => HighlightTag::Attribute.into(),
391 INT_NUMBER | FLOAT_NUMBER => HighlightTag::NumericLiteral.into(),
392 BYTE => HighlightTag::ByteLiteral.into(),
393 CHAR => HighlightTag::CharLiteral.into(),
395 let h = Highlight::new(HighlightTag::Lifetime);
396 match element.parent().map(|it| it.kind()) {
397 Some(LIFETIME_PARAM) | Some(LABEL) => h | HighlightModifier::Definition,
402 k if k.is_keyword() => {
403 let h = Highlight::new(HighlightTag::Keyword);
413 | T![in] => h | HighlightModifier::ControlFlow,
414 T![for] if !is_child_of_impl(element) => h | HighlightModifier::ControlFlow,
415 T![unsafe] => h | HighlightModifier::Unsafe,
416 T![true] | T![false] => HighlightTag::BoolLiteral.into(),
424 return Some((highlight, binding_hash));
426 fn calc_binding_hash(name: &Name, shadow_count: u32) -> u64 {
427 fn hash<T: std::hash::Hash + std::fmt::Debug>(x: T) -> u64 {
428 use std::{collections::hash_map::DefaultHasher, hash::Hasher};
430 let mut hasher = DefaultHasher::new();
435 hash((name, shadow_count))
439 fn is_child_of_impl(element: SyntaxElement) -> bool {
440 match element.parent() {
441 Some(e) => e.kind() == IMPL_DEF,
446 fn highlight_name(db: &RootDatabase, def: Definition) -> Highlight {
448 Definition::Macro(_) => HighlightTag::Macro,
449 Definition::Field(_) => HighlightTag::Field,
450 Definition::ModuleDef(def) => match def {
451 hir::ModuleDef::Module(_) => HighlightTag::Module,
452 hir::ModuleDef::Function(_) => HighlightTag::Function,
453 hir::ModuleDef::Adt(hir::Adt::Struct(_)) => HighlightTag::Struct,
454 hir::ModuleDef::Adt(hir::Adt::Enum(_)) => HighlightTag::Enum,
455 hir::ModuleDef::Adt(hir::Adt::Union(_)) => HighlightTag::Union,
456 hir::ModuleDef::EnumVariant(_) => HighlightTag::EnumVariant,
457 hir::ModuleDef::Const(_) => HighlightTag::Constant,
458 hir::ModuleDef::Trait(_) => HighlightTag::Trait,
459 hir::ModuleDef::TypeAlias(_) => HighlightTag::TypeAlias,
460 hir::ModuleDef::BuiltinType(_) => HighlightTag::BuiltinType,
461 hir::ModuleDef::Static(s) => {
462 let mut h = Highlight::new(HighlightTag::Static);
464 h |= HighlightModifier::Mutable;
469 Definition::SelfType(_) => HighlightTag::SelfType,
470 Definition::TypeParam(_) => HighlightTag::TypeParam,
471 // FIXME: distinguish between locals and parameters
472 Definition::Local(local) => {
473 let mut h = Highlight::new(HighlightTag::Local);
474 if local.is_mut(db) || local.ty(db).is_mutable_reference() {
475 h |= HighlightModifier::Mutable;
483 fn highlight_name_by_syntax(name: ast::Name) -> Highlight {
484 let default = HighlightTag::UnresolvedReference;
486 let parent = match name.syntax().parent() {
488 _ => return default.into(),
491 let tag = match parent.kind() {
492 STRUCT_DEF => HighlightTag::Struct,
493 ENUM_DEF => HighlightTag::Enum,
494 UNION_DEF => HighlightTag::Union,
495 TRAIT_DEF => HighlightTag::Trait,
496 TYPE_ALIAS_DEF => HighlightTag::TypeAlias,
497 TYPE_PARAM => HighlightTag::TypeParam,
498 RECORD_FIELD_DEF => HighlightTag::Field,
499 MODULE => HighlightTag::Module,
500 FN_DEF => HighlightTag::Function,
501 CONST_DEF => HighlightTag::Constant,
502 STATIC_DEF => HighlightTag::Static,
503 ENUM_VARIANT => HighlightTag::EnumVariant,
504 BIND_PAT => HighlightTag::Local,
511 fn highlight_injection(
512 acc: &mut HighlightedRangeStack,
513 sema: &Semantics<RootDatabase>,
514 literal: ast::RawString,
515 expanded: SyntaxToken,
517 let active_parameter = ActiveParameter::at_token(&sema, expanded)?;
518 if !active_parameter.name.starts_with("ra_fixture") {
521 let value = literal.value()?;
522 let (analysis, tmp_file_id) = Analysis::from_single_file(value);
524 if let Some(range) = literal.open_quote_text_range() {
525 acc.add(HighlightedRange {
527 highlight: HighlightTag::StringLiteral.into(),
532 for mut h in analysis.highlight(tmp_file_id).unwrap() {
533 if let Some(r) = literal.map_range_up(h.range) {
539 if let Some(range) = literal.close_quote_text_range() {
540 acc.add(HighlightedRange {
542 highlight: HighlightTag::StringLiteral.into(),