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(),
172 WalkEvent::Leave(Some(mc)) => {
173 assert!(current_macro_call == Some(mc));
174 current_macro_call = None;
175 format_string = None;
181 let element = match event {
182 WalkEvent::Enter(it) => it,
183 WalkEvent::Leave(_) => continue,
186 let range = element.text_range();
188 let element_to_highlight = if current_macro_call.is_some() {
189 // Inside a macro -- expand it first
190 let token = match element.clone().into_token() {
191 Some(it) if it.parent().kind() == TOKEN_TREE => it,
194 let token = sema.descend_into_macros(token.clone());
195 let parent = token.parent();
197 // Check if macro takes a format string and remember it for highlighting later.
198 // The macros that accept a format string expand to a compiler builtin macros
199 // `format_args` and `format_args_nl`.
200 if let Some(fmt_macro_call) = parent.parent().and_then(ast::MacroCall::cast) {
202 fmt_macro_call.path().and_then(|p| p.segment()).and_then(|s| s.name_ref())
204 match name.text().as_str() {
205 "format_args" | "format_args_nl" => {
206 format_string = parent
207 .children_with_tokens()
208 .filter(|t| t.kind() != WHITESPACE)
211 ast::String::can_cast(e.kind())
212 || ast::RawString::can_cast(e.kind())
220 // We only care Name and Name_ref
221 match (token.kind(), parent.kind()) {
222 (IDENT, NAME) | (IDENT, NAME_REF) => parent.into(),
229 if let Some(token) = element.as_token().cloned().and_then(ast::RawString::cast) {
230 let expanded = element_to_highlight.as_token().unwrap().clone();
231 if highlight_injection(&mut stack, &sema, token, expanded).is_some() {
236 let is_format_string = format_string.as_ref() == Some(&element_to_highlight);
238 if let Some((highlight, binding_hash)) =
239 highlight_element(&sema, &mut bindings_shadow_count, element_to_highlight.clone())
241 stack.add(HighlightedRange { range, highlight, binding_hash });
242 if let Some(string) =
243 element_to_highlight.as_token().cloned().and_then(ast::String::cast)
246 if is_format_string {
247 string.lex_format_specifier(|piece_range, kind| {
248 if let Some(highlight) = highlight_format_specifier(kind) {
249 stack.add(HighlightedRange {
250 range: piece_range + range.start(),
251 highlight: highlight.into(),
258 } else if let Some(string) =
259 element_to_highlight.as_token().cloned().and_then(ast::RawString::cast)
262 if is_format_string {
263 string.lex_format_specifier(|piece_range, kind| {
264 if let Some(highlight) = highlight_format_specifier(kind) {
265 stack.add(HighlightedRange {
266 range: piece_range + range.start(),
267 highlight: highlight.into(),
281 fn highlight_format_specifier(kind: FormatSpecifier) -> Option<HighlightTag> {
283 FormatSpecifier::Open
284 | FormatSpecifier::Close
285 | FormatSpecifier::Colon
286 | FormatSpecifier::Fill
287 | FormatSpecifier::Align
288 | FormatSpecifier::Sign
289 | FormatSpecifier::NumberSign
290 | FormatSpecifier::DollarSign
291 | FormatSpecifier::Dot
292 | FormatSpecifier::Asterisk
293 | FormatSpecifier::QuestionMark => HighlightTag::FormatSpecifier,
294 FormatSpecifier::Integer | FormatSpecifier::Zero => HighlightTag::NumericLiteral,
295 FormatSpecifier::Identifier => HighlightTag::Local,
299 fn macro_call_range(macro_call: &ast::MacroCall) -> Option<TextRange> {
300 let path = macro_call.path()?;
301 let name_ref = path.segment()?.name_ref()?;
303 let range_start = name_ref.syntax().text_range().start();
304 let mut range_end = name_ref.syntax().text_range().end();
305 for sibling in path.syntax().siblings_with_tokens(Direction::Next) {
306 match sibling.kind() {
307 T![!] | IDENT => range_end = sibling.text_range().end(),
312 Some(TextRange::new(range_start, range_end))
315 fn highlight_element(
316 sema: &Semantics<RootDatabase>,
317 bindings_shadow_count: &mut FxHashMap<Name, u32>,
318 element: SyntaxElement,
319 ) -> Option<(Highlight, Option<u64>)> {
321 let mut binding_hash = None;
322 let highlight: Highlight = match element.kind() {
324 bindings_shadow_count.clear();
328 // Highlight definitions depending on the "type" of the definition.
330 let name = element.into_node().and_then(ast::Name::cast).unwrap();
331 let name_kind = classify_name(sema, &name);
333 if let Some(NameClass::Definition(Definition::Local(local))) = &name_kind {
334 if let Some(name) = local.name(db) {
335 let shadow_count = bindings_shadow_count.entry(name.clone()).or_default();
337 binding_hash = Some(calc_binding_hash(&name, *shadow_count))
342 Some(NameClass::Definition(def)) => {
343 highlight_name(db, def) | HighlightModifier::Definition
345 Some(NameClass::ConstReference(def)) => highlight_name(db, def),
346 None => highlight_name_by_syntax(name) | HighlightModifier::Definition,
350 // Highlight references like the definitions they resolve to
351 NAME_REF if element.ancestors().any(|it| it.kind() == ATTR) => return None,
353 let name_ref = element.into_node().and_then(ast::NameRef::cast).unwrap();
354 match classify_name_ref(sema, &name_ref) {
355 Some(name_kind) => match name_kind {
356 NameRefClass::Definition(def) => {
357 if let Definition::Local(local) = &def {
358 if let Some(name) = local.name(db) {
360 bindings_shadow_count.entry(name.clone()).or_default();
361 binding_hash = Some(calc_binding_hash(&name, *shadow_count))
364 highlight_name(db, def)
366 NameRefClass::FieldShorthand { .. } => HighlightTag::Field.into(),
368 None => HighlightTag::UnresolvedReference.into(),
372 // Simple token-based highlighting
373 COMMENT => HighlightTag::Comment.into(),
374 STRING | RAW_STRING | RAW_BYTE_STRING | BYTE_STRING => HighlightTag::StringLiteral.into(),
375 ATTR => HighlightTag::Attribute.into(),
376 INT_NUMBER | FLOAT_NUMBER => HighlightTag::NumericLiteral.into(),
377 BYTE => HighlightTag::ByteLiteral.into(),
378 CHAR => HighlightTag::CharLiteral.into(),
380 let h = Highlight::new(HighlightTag::Lifetime);
381 match element.parent().map(|it| it.kind()) {
382 Some(LIFETIME_PARAM) | Some(LABEL) => h | HighlightModifier::Definition,
387 k if k.is_keyword() => {
388 let h = Highlight::new(HighlightTag::Keyword);
398 | T![while] => h | HighlightModifier::ControlFlow,
399 T![unsafe] => h | HighlightModifier::Unsafe,
407 return Some((highlight, binding_hash));
409 fn calc_binding_hash(name: &Name, shadow_count: u32) -> u64 {
410 fn hash<T: std::hash::Hash + std::fmt::Debug>(x: T) -> u64 {
411 use std::{collections::hash_map::DefaultHasher, hash::Hasher};
413 let mut hasher = DefaultHasher::new();
418 hash((name, shadow_count))
422 fn highlight_name(db: &RootDatabase, def: Definition) -> Highlight {
424 Definition::Macro(_) => HighlightTag::Macro,
425 Definition::Field(_) => HighlightTag::Field,
426 Definition::ModuleDef(def) => match def {
427 hir::ModuleDef::Module(_) => HighlightTag::Module,
428 hir::ModuleDef::Function(_) => HighlightTag::Function,
429 hir::ModuleDef::Adt(hir::Adt::Struct(_)) => HighlightTag::Struct,
430 hir::ModuleDef::Adt(hir::Adt::Enum(_)) => HighlightTag::Enum,
431 hir::ModuleDef::Adt(hir::Adt::Union(_)) => HighlightTag::Union,
432 hir::ModuleDef::EnumVariant(_) => HighlightTag::EnumVariant,
433 hir::ModuleDef::Const(_) => HighlightTag::Constant,
434 hir::ModuleDef::Static(_) => HighlightTag::Static,
435 hir::ModuleDef::Trait(_) => HighlightTag::Trait,
436 hir::ModuleDef::TypeAlias(_) => HighlightTag::TypeAlias,
437 hir::ModuleDef::BuiltinType(_) => HighlightTag::BuiltinType,
439 Definition::SelfType(_) => HighlightTag::SelfType,
440 Definition::TypeParam(_) => HighlightTag::TypeParam,
441 // FIXME: distinguish between locals and parameters
442 Definition::Local(local) => {
443 let mut h = Highlight::new(HighlightTag::Local);
444 if local.is_mut(db) || local.ty(db).is_mutable_reference() {
445 h |= HighlightModifier::Mutable;
453 fn highlight_name_by_syntax(name: ast::Name) -> Highlight {
454 let default = HighlightTag::Function.into();
456 let parent = match name.syntax().parent() {
461 match parent.kind() {
462 STRUCT_DEF => HighlightTag::Struct.into(),
463 ENUM_DEF => HighlightTag::Enum.into(),
464 UNION_DEF => HighlightTag::Union.into(),
465 TRAIT_DEF => HighlightTag::Trait.into(),
466 TYPE_ALIAS_DEF => HighlightTag::TypeAlias.into(),
467 TYPE_PARAM => HighlightTag::TypeParam.into(),
468 RECORD_FIELD_DEF => HighlightTag::Field.into(),
473 fn highlight_injection(
474 acc: &mut HighlightedRangeStack,
475 sema: &Semantics<RootDatabase>,
476 literal: ast::RawString,
477 expanded: SyntaxToken,
479 let active_parameter = ActiveParameter::at_token(&sema, expanded)?;
480 if !active_parameter.name.starts_with("ra_fixture") {
483 let value = literal.value()?;
484 let (analysis, tmp_file_id) = Analysis::from_single_file(value);
486 if let Some(range) = literal.open_quote_text_range() {
487 acc.add(HighlightedRange {
489 highlight: HighlightTag::StringLiteral.into(),
494 for mut h in analysis.highlight(tmp_file_id).unwrap() {
495 if let Some(r) = literal.map_range_up(h.range) {
501 if let Some(range) = literal.close_quote_text_range() {
502 acc.add(HighlightedRange {
504 highlight: HighlightTag::StringLiteral.into(),