1 //! Implements syntax highlighting.
8 use hir::{Name, Semantics};
10 defs::{classify_name, NameDefinition},
15 ast::{self, 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, references::classify_name_ref, Analysis, FileId};
24 pub(crate) use html::highlight_as_html;
25 pub use tags::{Highlight, HighlightModifier, HighlightModifiers, HighlightTag};
28 pub struct HighlightedRange {
30 pub highlight: Highlight,
31 pub binding_hash: Option<u64>,
34 pub(crate) fn highlight(
37 range_to_highlight: Option<TextRange>,
38 ) -> Vec<HighlightedRange> {
39 let _p = profile("highlight");
40 let sema = Semantics::new(db);
42 // Determine the root based on the given range.
43 let (root, range_to_highlight) = {
44 let source_file = sema.parse(file_id);
45 match range_to_highlight {
47 let node = match source_file.syntax().covering_element(range) {
48 NodeOrToken::Node(it) => it,
49 NodeOrToken::Token(it) => it.parent(),
53 None => (source_file.syntax().clone(), source_file.syntax().text_range()),
57 let mut bindings_shadow_count: FxHashMap<Name, u32> = FxHashMap::default();
58 let mut res = Vec::new();
60 let mut current_macro_call: Option<ast::MacroCall> = None;
62 // Walk all nodes, keeping track of whether we are inside a macro or not.
63 // If in macro, expand it first and highlight the expanded code.
64 for event in root.preorder_with_tokens() {
65 let event_range = match &event {
66 WalkEvent::Enter(it) => it.text_range(),
67 WalkEvent::Leave(it) => it.text_range(),
70 // Element outside of the viewport, no need to highlight
71 if range_to_highlight.intersection(&event_range).is_none() {
75 // Track "inside macro" state
76 match event.clone().map(|it| it.into_node().and_then(ast::MacroCall::cast)) {
77 WalkEvent::Enter(Some(mc)) => {
78 current_macro_call = Some(mc.clone());
79 if let Some(range) = macro_call_range(&mc) {
80 res.push(HighlightedRange {
82 highlight: HighlightTag::Macro.into(),
88 WalkEvent::Leave(Some(mc)) => {
89 assert!(current_macro_call == Some(mc));
90 current_macro_call = None;
96 let element = match event {
97 WalkEvent::Enter(it) => it,
98 WalkEvent::Leave(_) => continue,
101 let range = element.text_range();
103 let element_to_highlight = if current_macro_call.is_some() {
104 // Inside a macro -- expand it first
105 let token = match element.clone().into_token() {
106 Some(it) if it.parent().kind() == TOKEN_TREE => it,
109 let token = sema.descend_into_macros(token.clone());
110 let parent = token.parent();
111 // We only care Name and Name_ref
112 match (token.kind(), parent.kind()) {
113 (IDENT, NAME) | (IDENT, NAME_REF) => parent.into(),
120 if let Some(token) = element.as_token().cloned().and_then(ast::RawString::cast) {
121 let expanded = element_to_highlight.as_token().unwrap().clone();
122 if highlight_injection(&mut res, &sema, token, expanded).is_some() {
123 eprintln!("res = {:?}", res);
128 if let Some((highlight, binding_hash)) =
129 highlight_element(&sema, &mut bindings_shadow_count, element_to_highlight)
131 res.push(HighlightedRange { range, highlight, binding_hash });
138 fn macro_call_range(macro_call: &ast::MacroCall) -> Option<TextRange> {
139 let path = macro_call.path()?;
140 let name_ref = path.segment()?.name_ref()?;
142 let range_start = name_ref.syntax().text_range().start();
143 let mut range_end = name_ref.syntax().text_range().end();
144 for sibling in path.syntax().siblings_with_tokens(Direction::Next) {
145 match sibling.kind() {
146 T![!] | IDENT => range_end = sibling.text_range().end(),
151 Some(TextRange::from_to(range_start, range_end))
154 fn highlight_element(
155 sema: &Semantics<RootDatabase>,
156 bindings_shadow_count: &mut FxHashMap<Name, u32>,
157 element: SyntaxElement,
158 ) -> Option<(Highlight, Option<u64>)> {
160 let mut binding_hash = None;
161 let highlight: Highlight = match element.kind() {
163 bindings_shadow_count.clear();
167 // Highlight definitions depending on the "type" of the definition.
169 let name = element.into_node().and_then(ast::Name::cast).unwrap();
170 let name_kind = classify_name(sema, &name);
172 if let Some(NameDefinition::Local(local)) = &name_kind {
173 if let Some(name) = local.name(db) {
174 let shadow_count = bindings_shadow_count.entry(name.clone()).or_default();
176 binding_hash = Some(calc_binding_hash(&name, *shadow_count))
181 Some(name_kind) => highlight_name(db, name_kind),
182 None => highlight_name_by_syntax(name),
186 // Highlight references like the definitions they resolve to
188 // Special-case field init shorthand
189 NAME_REF if element.parent().and_then(ast::RecordField::cast).is_some() => {
190 HighlightTag::Field.into()
192 NAME_REF if element.ancestors().any(|it| it.kind() == ATTR) => return None,
194 let name_ref = element.into_node().and_then(ast::NameRef::cast).unwrap();
195 let name_kind = classify_name_ref(sema, &name_ref)?;
197 if let NameDefinition::Local(local) = &name_kind {
198 if let Some(name) = local.name(db) {
199 let shadow_count = bindings_shadow_count.entry(name.clone()).or_default();
200 binding_hash = Some(calc_binding_hash(&name, *shadow_count))
204 highlight_name(db, name_kind)
207 // Simple token-based highlighting
208 COMMENT => HighlightTag::Comment.into(),
209 STRING | RAW_STRING | RAW_BYTE_STRING | BYTE_STRING => HighlightTag::LiteralString.into(),
210 ATTR => HighlightTag::Attribute.into(),
211 INT_NUMBER | FLOAT_NUMBER => HighlightTag::LiteralNumeric.into(),
212 BYTE => HighlightTag::LiteralByte.into(),
213 CHAR => HighlightTag::LiteralChar.into(),
214 LIFETIME => HighlightTag::TypeLifetime.into(),
216 k if k.is_keyword() => {
217 let h = Highlight::new(HighlightTag::Keyword);
227 | T![while] => h | HighlightModifier::Control,
228 T![unsafe] => h | HighlightModifier::Unsafe,
236 return Some((highlight, binding_hash));
238 fn calc_binding_hash(name: &Name, shadow_count: u32) -> u64 {
239 fn hash<T: std::hash::Hash + std::fmt::Debug>(x: T) -> u64 {
240 use std::{collections::hash_map::DefaultHasher, hash::Hasher};
242 let mut hasher = DefaultHasher::new();
247 hash((name, shadow_count))
251 fn highlight_name(db: &RootDatabase, def: NameDefinition) -> Highlight {
253 NameDefinition::Macro(_) => HighlightTag::Macro,
254 NameDefinition::StructField(_) => HighlightTag::Field,
255 NameDefinition::ModuleDef(def) => match def {
256 hir::ModuleDef::Module(_) => HighlightTag::Module,
257 hir::ModuleDef::Function(_) => HighlightTag::Function,
258 hir::ModuleDef::Adt(hir::Adt::Struct(_)) => HighlightTag::Struct,
259 hir::ModuleDef::Adt(hir::Adt::Enum(_)) => HighlightTag::Enum,
260 hir::ModuleDef::Adt(hir::Adt::Union(_)) => HighlightTag::Union,
261 hir::ModuleDef::EnumVariant(_) => HighlightTag::Constant,
262 hir::ModuleDef::Const(_) => HighlightTag::Constant,
263 hir::ModuleDef::Static(_) => HighlightTag::Constant,
264 hir::ModuleDef::Trait(_) => HighlightTag::Trait,
265 hir::ModuleDef::TypeAlias(_) => HighlightTag::TypeAlias,
266 hir::ModuleDef::BuiltinType(_) => HighlightTag::BuiltinType,
268 NameDefinition::SelfType(_) => HighlightTag::TypeSelf,
269 NameDefinition::TypeParam(_) => HighlightTag::TypeParam,
270 NameDefinition::Local(local) => {
271 let mut h = Highlight::new(HighlightTag::Variable);
272 if local.is_mut(db) || local.ty(db).is_mutable_reference() {
273 h |= HighlightModifier::Mutable;
281 fn highlight_name_by_syntax(name: ast::Name) -> Highlight {
282 let default = HighlightTag::Function.into();
284 let parent = match name.syntax().parent() {
289 match parent.kind() {
290 STRUCT_DEF => HighlightTag::Struct.into(),
291 ENUM_DEF => HighlightTag::Enum.into(),
292 TRAIT_DEF => HighlightTag::Trait.into(),
293 TYPE_ALIAS_DEF => HighlightTag::TypeAlias.into(),
294 TYPE_PARAM => HighlightTag::TypeParam.into(),
295 RECORD_FIELD_DEF => HighlightTag::Field.into(),
300 fn highlight_injection(
301 acc: &mut Vec<HighlightedRange>,
302 sema: &Semantics<RootDatabase>,
303 literal: ast::RawString,
304 expanded: SyntaxToken,
306 let call_info = call_info_for_token(&sema, expanded)?;
307 let idx = call_info.active_parameter?;
308 let name = call_info.signature.parameter_names.get(idx)?;
309 if name != "ra_fixture" {
312 let value = literal.value()?;
313 let (analysis, tmp_file_id) = Analysis::from_single_file(value);
315 if let Some(range) = literal.open_quote_text_range() {
316 acc.push(HighlightedRange {
318 highlight: HighlightTag::LiteralString.into(),
323 for mut h in analysis.highlight(tmp_file_id).unwrap() {
324 if let Some(r) = literal.map_range_up(h.range) {
330 if let Some(range) = literal.close_quote_text_range() {
331 acc.push(HighlightedRange {
333 highlight: HighlightTag::LiteralString.into(),