1 //! Implements syntax highlighting.
8 use hir::{Name, Semantics};
10 defs::{classify_name, NameClass, NameDefinition},
15 ast::{self, HasQuotes, HasStringValue},
16 AstNode, AstToken, Direction, NodeOrToken, SyntaxElement,
18 SyntaxToken, TextRange, WalkEvent, T,
20 use rustc_hash::FxHashMap;
23 call_info::call_info_for_token,
24 references::{classify_name_ref, NameRefClass},
28 pub(crate) use html::highlight_as_html;
29 pub use tags::{Highlight, HighlightModifier, HighlightModifiers, HighlightTag};
32 pub struct HighlightedRange {
34 pub highlight: Highlight,
35 pub binding_hash: Option<u64>,
38 pub(crate) fn highlight(
41 range_to_highlight: Option<TextRange>,
42 ) -> Vec<HighlightedRange> {
43 let _p = profile("highlight");
44 let sema = Semantics::new(db);
46 // Determine the root based on the given range.
47 let (root, range_to_highlight) = {
48 let source_file = sema.parse(file_id);
49 match range_to_highlight {
51 let node = match source_file.syntax().covering_element(range) {
52 NodeOrToken::Node(it) => it,
53 NodeOrToken::Token(it) => it.parent(),
57 None => (source_file.syntax().clone(), source_file.syntax().text_range()),
61 let mut bindings_shadow_count: FxHashMap<Name, u32> = FxHashMap::default();
62 let mut res = Vec::new();
64 let mut current_macro_call: Option<ast::MacroCall> = None;
66 // Walk all nodes, keeping track of whether we are inside a macro or not.
67 // If in macro, expand it first and highlight the expanded code.
68 for event in root.preorder_with_tokens() {
69 let event_range = match &event {
70 WalkEvent::Enter(it) => it.text_range(),
71 WalkEvent::Leave(it) => it.text_range(),
74 // Element outside of the viewport, no need to highlight
75 if range_to_highlight.intersection(&event_range).is_none() {
79 // Track "inside macro" state
80 match event.clone().map(|it| it.into_node().and_then(ast::MacroCall::cast)) {
81 WalkEvent::Enter(Some(mc)) => {
82 current_macro_call = Some(mc.clone());
83 if let Some(range) = macro_call_range(&mc) {
84 res.push(HighlightedRange {
86 highlight: HighlightTag::Macro.into(),
92 WalkEvent::Leave(Some(mc)) => {
93 assert!(current_macro_call == Some(mc));
94 current_macro_call = None;
100 let element = match event {
101 WalkEvent::Enter(it) => it,
102 WalkEvent::Leave(_) => continue,
105 let range = element.text_range();
107 let element_to_highlight = if current_macro_call.is_some() {
108 // Inside a macro -- expand it first
109 let token = match element.clone().into_token() {
110 Some(it) if it.parent().kind() == TOKEN_TREE => it,
113 let token = sema.descend_into_macros(token.clone());
114 let parent = token.parent();
115 // We only care Name and Name_ref
116 match (token.kind(), parent.kind()) {
117 (IDENT, NAME) | (IDENT, NAME_REF) => parent.into(),
124 if let Some(token) = element.as_token().cloned().and_then(ast::RawString::cast) {
125 let expanded = element_to_highlight.as_token().unwrap().clone();
126 if highlight_injection(&mut res, &sema, token, expanded).is_some() {
131 if let Some((highlight, binding_hash)) =
132 highlight_element(&sema, &mut bindings_shadow_count, element_to_highlight)
134 res.push(HighlightedRange { range, highlight, binding_hash });
141 fn macro_call_range(macro_call: &ast::MacroCall) -> Option<TextRange> {
142 let path = macro_call.path()?;
143 let name_ref = path.segment()?.name_ref()?;
145 let range_start = name_ref.syntax().text_range().start();
146 let mut range_end = name_ref.syntax().text_range().end();
147 for sibling in path.syntax().siblings_with_tokens(Direction::Next) {
148 match sibling.kind() {
149 T![!] | IDENT => range_end = sibling.text_range().end(),
154 Some(TextRange::from_to(range_start, range_end))
157 fn highlight_element(
158 sema: &Semantics<RootDatabase>,
159 bindings_shadow_count: &mut FxHashMap<Name, u32>,
160 element: SyntaxElement,
161 ) -> Option<(Highlight, Option<u64>)> {
163 let mut binding_hash = None;
164 let highlight: Highlight = match element.kind() {
166 bindings_shadow_count.clear();
170 // Highlight definitions depending on the "type" of the definition.
172 let name = element.into_node().and_then(ast::Name::cast).unwrap();
173 let name_kind = classify_name(sema, &name);
175 if let Some(NameClass::NameDefinition(NameDefinition::Local(local))) = &name_kind {
176 if let Some(name) = local.name(db) {
177 let shadow_count = bindings_shadow_count.entry(name.clone()).or_default();
179 binding_hash = Some(calc_binding_hash(&name, *shadow_count))
184 Some(NameClass::NameDefinition(def)) => {
185 highlight_name(db, def) | HighlightModifier::Definition
187 Some(NameClass::ConstReference(def)) => highlight_name(db, def),
188 None => highlight_name_by_syntax(name) | HighlightModifier::Definition,
192 // Highlight references like the definitions they resolve to
193 NAME_REF if element.ancestors().any(|it| it.kind() == ATTR) => return None,
195 let name_ref = element.into_node().and_then(ast::NameRef::cast).unwrap();
196 let name_kind = classify_name_ref(sema, &name_ref)?;
199 NameRefClass::NameDefinition(def) => {
200 if let NameDefinition::Local(local) = &def {
201 if let Some(name) = local.name(db) {
203 bindings_shadow_count.entry(name.clone()).or_default();
204 binding_hash = Some(calc_binding_hash(&name, *shadow_count))
207 highlight_name(db, def)
209 NameRefClass::FieldShorthand { .. } => HighlightTag::Field.into(),
213 // Simple token-based highlighting
214 COMMENT => HighlightTag::Comment.into(),
215 STRING | RAW_STRING | RAW_BYTE_STRING | BYTE_STRING => HighlightTag::StringLiteral.into(),
216 ATTR => HighlightTag::Attribute.into(),
217 INT_NUMBER | FLOAT_NUMBER => HighlightTag::NumericLiteral.into(),
218 BYTE => HighlightTag::ByteLiteral.into(),
219 CHAR => HighlightTag::CharLiteral.into(),
221 let h = Highlight::new(HighlightTag::Lifetime);
222 match element.parent().map(|it| it.kind()) {
223 Some(LIFETIME_PARAM) | Some(LABEL) => h | HighlightModifier::Definition,
228 k if k.is_keyword() => {
229 let h = Highlight::new(HighlightTag::Keyword);
239 | T![while] => h | HighlightModifier::Control,
240 T![unsafe] => h | HighlightModifier::Unsafe,
248 return Some((highlight, binding_hash));
250 fn calc_binding_hash(name: &Name, shadow_count: u32) -> u64 {
251 fn hash<T: std::hash::Hash + std::fmt::Debug>(x: T) -> u64 {
252 use std::{collections::hash_map::DefaultHasher, hash::Hasher};
254 let mut hasher = DefaultHasher::new();
259 hash((name, shadow_count))
263 fn highlight_name(db: &RootDatabase, def: NameDefinition) -> Highlight {
265 NameDefinition::Macro(_) => HighlightTag::Macro,
266 NameDefinition::StructField(_) => HighlightTag::Field,
267 NameDefinition::ModuleDef(def) => match def {
268 hir::ModuleDef::Module(_) => HighlightTag::Module,
269 hir::ModuleDef::Function(_) => HighlightTag::Function,
270 hir::ModuleDef::Adt(hir::Adt::Struct(_)) => HighlightTag::Struct,
271 hir::ModuleDef::Adt(hir::Adt::Enum(_)) => HighlightTag::Enum,
272 hir::ModuleDef::Adt(hir::Adt::Union(_)) => HighlightTag::Union,
273 hir::ModuleDef::EnumVariant(_) => HighlightTag::EnumVariant,
274 hir::ModuleDef::Const(_) => HighlightTag::Constant,
275 hir::ModuleDef::Static(_) => HighlightTag::Static,
276 hir::ModuleDef::Trait(_) => HighlightTag::Trait,
277 hir::ModuleDef::TypeAlias(_) => HighlightTag::TypeAlias,
278 hir::ModuleDef::BuiltinType(_) => HighlightTag::BuiltinType,
280 NameDefinition::SelfType(_) => HighlightTag::SelfType,
281 NameDefinition::TypeParam(_) => HighlightTag::TypeParam,
282 // FIXME: distinguish between locals and parameters
283 NameDefinition::Local(local) => {
284 let mut h = Highlight::new(HighlightTag::Local);
285 if local.is_mut(db) || local.ty(db).is_mutable_reference() {
286 h |= HighlightModifier::Mutable;
294 fn highlight_name_by_syntax(name: ast::Name) -> Highlight {
295 let default = HighlightTag::Function.into();
297 let parent = match name.syntax().parent() {
302 match parent.kind() {
303 STRUCT_DEF => HighlightTag::Struct.into(),
304 ENUM_DEF => HighlightTag::Enum.into(),
305 UNION_DEF => HighlightTag::Union.into(),
306 TRAIT_DEF => HighlightTag::Trait.into(),
307 TYPE_ALIAS_DEF => HighlightTag::TypeAlias.into(),
308 TYPE_PARAM => HighlightTag::TypeParam.into(),
309 RECORD_FIELD_DEF => HighlightTag::Field.into(),
314 fn highlight_injection(
315 acc: &mut Vec<HighlightedRange>,
316 sema: &Semantics<RootDatabase>,
317 literal: ast::RawString,
318 expanded: SyntaxToken,
320 let call_info = call_info_for_token(&sema, expanded)?;
321 let idx = call_info.active_parameter?;
322 let name = call_info.signature.parameter_names.get(idx)?;
323 if name != "ra_fixture" {
326 let value = literal.value()?;
327 let (analysis, tmp_file_id) = Analysis::from_single_file(value);
329 if let Some(range) = literal.open_quote_text_range() {
330 acc.push(HighlightedRange {
332 highlight: HighlightTag::StringLiteral.into(),
337 for mut h in analysis.highlight(tmp_file_id).unwrap() {
338 if let Some(r) = literal.map_range_up(h.range) {
344 if let Some(range) = literal.close_quote_text_range() {
345 acc.push(HighlightedRange {
347 highlight: HighlightTag::StringLiteral.into(),