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::call_info_for_token, 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 && children.first().unwrap().range.is_subrange(&prev.last().unwrap().range);
65 if !needs_flattening {
66 prev.extend(children);
68 let mut parent = prev.pop().unwrap();
70 assert!(ele.range.is_subrange(&parent.range));
71 let mut cloned = parent.clone();
72 parent.range = TextRange::from_to(parent.range.start(), ele.range.start());
73 cloned.range = TextRange::from_to(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.intersection(&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 remeber 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 =
237 format_string.as_ref().map(|fs| fs == &element_to_highlight).unwrap_or_default();
239 if let Some((highlight, binding_hash)) =
240 highlight_element(&sema, &mut bindings_shadow_count, element_to_highlight.clone())
242 stack.add(HighlightedRange { range, highlight, binding_hash });
243 if let Some(string) =
244 element_to_highlight.as_token().cloned().and_then(ast::String::cast)
247 if is_format_string {
248 string.lex_format_specifier(&mut |piece_range, kind| {
249 let highlight = match kind {
250 FormatSpecifier::Open
251 | FormatSpecifier::Close
252 | FormatSpecifier::Colon
253 | FormatSpecifier::Fill
254 | FormatSpecifier::Align
255 | FormatSpecifier::Sign
256 | FormatSpecifier::NumberSign
257 | FormatSpecifier::DollarSign
258 | FormatSpecifier::Dot
259 | FormatSpecifier::Asterisk
260 | FormatSpecifier::QuestionMark => HighlightTag::Attribute,
261 FormatSpecifier::Integer | FormatSpecifier::Zero => {
262 HighlightTag::NumericLiteral
264 FormatSpecifier::Identifier => HighlightTag::Local,
266 stack.add(HighlightedRange {
267 range: piece_range + range.start(),
268 highlight: highlight.into(),
281 fn macro_call_range(macro_call: &ast::MacroCall) -> Option<TextRange> {
282 let path = macro_call.path()?;
283 let name_ref = path.segment()?.name_ref()?;
285 let range_start = name_ref.syntax().text_range().start();
286 let mut range_end = name_ref.syntax().text_range().end();
287 for sibling in path.syntax().siblings_with_tokens(Direction::Next) {
288 match sibling.kind() {
289 T![!] | IDENT => range_end = sibling.text_range().end(),
294 Some(TextRange::from_to(range_start, range_end))
297 fn highlight_element(
298 sema: &Semantics<RootDatabase>,
299 bindings_shadow_count: &mut FxHashMap<Name, u32>,
300 element: SyntaxElement,
301 ) -> Option<(Highlight, Option<u64>)> {
303 let mut binding_hash = None;
304 let highlight: Highlight = match element.kind() {
306 bindings_shadow_count.clear();
310 // Highlight definitions depending on the "type" of the definition.
312 let name = element.into_node().and_then(ast::Name::cast).unwrap();
313 let name_kind = classify_name(sema, &name);
315 if let Some(NameClass::Definition(Definition::Local(local))) = &name_kind {
316 if let Some(name) = local.name(db) {
317 let shadow_count = bindings_shadow_count.entry(name.clone()).or_default();
319 binding_hash = Some(calc_binding_hash(&name, *shadow_count))
324 Some(NameClass::Definition(def)) => {
325 highlight_name(db, def) | HighlightModifier::Definition
327 Some(NameClass::ConstReference(def)) => highlight_name(db, def),
328 None => highlight_name_by_syntax(name) | HighlightModifier::Definition,
332 // Highlight references like the definitions they resolve to
333 NAME_REF if element.ancestors().any(|it| it.kind() == ATTR) => return None,
335 let name_ref = element.into_node().and_then(ast::NameRef::cast).unwrap();
336 let name_kind = classify_name_ref(sema, &name_ref)?;
339 NameRefClass::Definition(def) => {
340 if let Definition::Local(local) = &def {
341 if let Some(name) = local.name(db) {
343 bindings_shadow_count.entry(name.clone()).or_default();
344 binding_hash = Some(calc_binding_hash(&name, *shadow_count))
347 highlight_name(db, def)
349 NameRefClass::FieldShorthand { .. } => HighlightTag::Field.into(),
353 // Simple token-based highlighting
354 COMMENT => HighlightTag::Comment.into(),
355 STRING | RAW_STRING | RAW_BYTE_STRING | BYTE_STRING => HighlightTag::StringLiteral.into(),
356 ATTR => HighlightTag::Attribute.into(),
357 INT_NUMBER | FLOAT_NUMBER => HighlightTag::NumericLiteral.into(),
358 BYTE => HighlightTag::ByteLiteral.into(),
359 CHAR => HighlightTag::CharLiteral.into(),
361 let h = Highlight::new(HighlightTag::Lifetime);
362 match element.parent().map(|it| it.kind()) {
363 Some(LIFETIME_PARAM) | Some(LABEL) => h | HighlightModifier::Definition,
368 k if k.is_keyword() => {
369 let h = Highlight::new(HighlightTag::Keyword);
379 | T![while] => h | HighlightModifier::ControlFlow,
380 T![unsafe] => h | HighlightModifier::Unsafe,
388 return Some((highlight, binding_hash));
390 fn calc_binding_hash(name: &Name, shadow_count: u32) -> u64 {
391 fn hash<T: std::hash::Hash + std::fmt::Debug>(x: T) -> u64 {
392 use std::{collections::hash_map::DefaultHasher, hash::Hasher};
394 let mut hasher = DefaultHasher::new();
399 hash((name, shadow_count))
403 fn highlight_name(db: &RootDatabase, def: Definition) -> Highlight {
405 Definition::Macro(_) => HighlightTag::Macro,
406 Definition::StructField(_) => HighlightTag::Field,
407 Definition::ModuleDef(def) => match def {
408 hir::ModuleDef::Module(_) => HighlightTag::Module,
409 hir::ModuleDef::Function(_) => HighlightTag::Function,
410 hir::ModuleDef::Adt(hir::Adt::Struct(_)) => HighlightTag::Struct,
411 hir::ModuleDef::Adt(hir::Adt::Enum(_)) => HighlightTag::Enum,
412 hir::ModuleDef::Adt(hir::Adt::Union(_)) => HighlightTag::Union,
413 hir::ModuleDef::EnumVariant(_) => HighlightTag::EnumVariant,
414 hir::ModuleDef::Const(_) => HighlightTag::Constant,
415 hir::ModuleDef::Static(_) => HighlightTag::Static,
416 hir::ModuleDef::Trait(_) => HighlightTag::Trait,
417 hir::ModuleDef::TypeAlias(_) => HighlightTag::TypeAlias,
418 hir::ModuleDef::BuiltinType(_) => HighlightTag::BuiltinType,
420 Definition::SelfType(_) => HighlightTag::SelfType,
421 Definition::TypeParam(_) => HighlightTag::TypeParam,
422 // FIXME: distinguish between locals and parameters
423 Definition::Local(local) => {
424 let mut h = Highlight::new(HighlightTag::Local);
425 if local.is_mut(db) || local.ty(db).is_mutable_reference() {
426 h |= HighlightModifier::Mutable;
434 fn highlight_name_by_syntax(name: ast::Name) -> Highlight {
435 let default = HighlightTag::Function.into();
437 let parent = match name.syntax().parent() {
442 match parent.kind() {
443 STRUCT_DEF => HighlightTag::Struct.into(),
444 ENUM_DEF => HighlightTag::Enum.into(),
445 UNION_DEF => HighlightTag::Union.into(),
446 TRAIT_DEF => HighlightTag::Trait.into(),
447 TYPE_ALIAS_DEF => HighlightTag::TypeAlias.into(),
448 TYPE_PARAM => HighlightTag::TypeParam.into(),
449 RECORD_FIELD_DEF => HighlightTag::Field.into(),
454 fn highlight_injection(
455 acc: &mut HighlightedRangeStack,
456 sema: &Semantics<RootDatabase>,
457 literal: ast::RawString,
458 expanded: SyntaxToken,
460 let call_info = call_info_for_token(&sema, expanded)?;
461 let idx = call_info.active_parameter?;
462 let name = call_info.signature.parameter_names.get(idx)?;
463 if !name.starts_with("ra_fixture") {
466 let value = literal.value()?;
467 let (analysis, tmp_file_id) = Analysis::from_single_file(value);
469 if let Some(range) = literal.open_quote_text_range() {
470 acc.add(HighlightedRange {
472 highlight: HighlightTag::StringLiteral.into(),
477 for mut h in analysis.highlight(tmp_file_id).unwrap() {
478 if let Some(r) = literal.map_range_up(h.range) {
484 if let Some(range) = literal.close_quote_text_range() {
485 acc.add(HighlightedRange {
487 highlight: HighlightTag::StringLiteral.into(),