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;
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() {
127 if let Some((highlight, binding_hash)) =
128 highlight_element(&sema, &mut bindings_shadow_count, element_to_highlight)
130 res.push(HighlightedRange { range, highlight, binding_hash });
137 fn macro_call_range(macro_call: &ast::MacroCall) -> Option<TextRange> {
138 let path = macro_call.path()?;
139 let name_ref = path.segment()?.name_ref()?;
141 let range_start = name_ref.syntax().text_range().start();
142 let mut range_end = name_ref.syntax().text_range().end();
143 for sibling in path.syntax().siblings_with_tokens(Direction::Next) {
144 match sibling.kind() {
145 T![!] | IDENT => range_end = sibling.text_range().end(),
150 Some(TextRange::from_to(range_start, range_end))
153 fn highlight_element(
154 sema: &Semantics<RootDatabase>,
155 bindings_shadow_count: &mut FxHashMap<Name, u32>,
156 element: SyntaxElement,
157 ) -> Option<(Highlight, Option<u64>)> {
159 let mut binding_hash = None;
160 let highlight: Highlight = match element.kind() {
162 bindings_shadow_count.clear();
166 // Highlight definitions depending on the "type" of the definition.
168 let name = element.into_node().and_then(ast::Name::cast).unwrap();
169 let name_kind = classify_name(sema, &name);
171 if let Some(NameClass::NameDefinition(NameDefinition::Local(local))) = &name_kind {
172 if let Some(name) = local.name(db) {
173 let shadow_count = bindings_shadow_count.entry(name.clone()).or_default();
175 binding_hash = Some(calc_binding_hash(&name, *shadow_count))
180 Some(NameClass::NameDefinition(def)) => {
181 highlight_name(db, def) | HighlightModifier::Definition
183 Some(NameClass::ConstReference(def)) => highlight_name(db, def),
184 None => highlight_name_by_syntax(name) | HighlightModifier::Definition,
188 // Highlight references like the definitions they resolve to
190 // Special-case field init shorthand
191 NAME_REF if element.parent().and_then(ast::RecordField::cast).is_some() => {
192 HighlightTag::Field.into()
194 NAME_REF if element.ancestors().any(|it| it.kind() == ATTR) => return None,
196 let name_ref = element.into_node().and_then(ast::NameRef::cast).unwrap();
197 let name_kind = classify_name_ref(sema, &name_ref)?;
199 if let NameDefinition::Local(local) = &name_kind {
200 if let Some(name) = local.name(db) {
201 let shadow_count = bindings_shadow_count.entry(name.clone()).or_default();
202 binding_hash = Some(calc_binding_hash(&name, *shadow_count))
206 highlight_name(db, name_kind)
209 // Simple token-based highlighting
210 COMMENT => HighlightTag::Comment.into(),
211 STRING | RAW_STRING | RAW_BYTE_STRING | BYTE_STRING => HighlightTag::StringLiteral.into(),
212 ATTR => HighlightTag::Attribute.into(),
213 INT_NUMBER | FLOAT_NUMBER => HighlightTag::NumericLiteral.into(),
214 BYTE => HighlightTag::ByteLiteral.into(),
215 CHAR => HighlightTag::CharLiteral.into(),
217 let h = Highlight::new(HighlightTag::Lifetime);
218 dbg!(match element.parent().map(|it| it.kind()) {
219 Some(LIFETIME_PARAM) | Some(LABEL) => h | HighlightModifier::Definition,
224 k if k.is_keyword() => {
225 let h = Highlight::new(HighlightTag::Keyword);
235 | T![while] => h | HighlightModifier::Control,
236 T![unsafe] => h | HighlightModifier::Unsafe,
244 return Some((highlight, binding_hash));
246 fn calc_binding_hash(name: &Name, shadow_count: u32) -> u64 {
247 fn hash<T: std::hash::Hash + std::fmt::Debug>(x: T) -> u64 {
248 use std::{collections::hash_map::DefaultHasher, hash::Hasher};
250 let mut hasher = DefaultHasher::new();
255 hash((name, shadow_count))
259 fn highlight_name(db: &RootDatabase, def: NameDefinition) -> Highlight {
261 NameDefinition::Macro(_) => HighlightTag::Macro,
262 NameDefinition::StructField(_) => HighlightTag::Field,
263 NameDefinition::ModuleDef(def) => match def {
264 hir::ModuleDef::Module(_) => HighlightTag::Module,
265 hir::ModuleDef::Function(_) => HighlightTag::Function,
266 hir::ModuleDef::Adt(hir::Adt::Struct(_)) => HighlightTag::Struct,
267 hir::ModuleDef::Adt(hir::Adt::Enum(_)) => HighlightTag::Enum,
268 hir::ModuleDef::Adt(hir::Adt::Union(_)) => HighlightTag::Union,
269 hir::ModuleDef::EnumVariant(_) => HighlightTag::EnumVariant,
270 hir::ModuleDef::Const(_) => HighlightTag::Constant,
271 hir::ModuleDef::Static(_) => HighlightTag::Static,
272 hir::ModuleDef::Trait(_) => HighlightTag::Trait,
273 hir::ModuleDef::TypeAlias(_) => HighlightTag::TypeAlias,
274 hir::ModuleDef::BuiltinType(_) => HighlightTag::BuiltinType,
276 NameDefinition::SelfType(_) => HighlightTag::SelfType,
277 NameDefinition::TypeParam(_) => HighlightTag::TypeParam,
278 // FIXME: distinguish between locals and parameters
279 NameDefinition::Local(local) => {
280 let mut h = Highlight::new(HighlightTag::Local);
281 if local.is_mut(db) || local.ty(db).is_mutable_reference() {
282 h |= HighlightModifier::Mutable;
290 fn highlight_name_by_syntax(name: ast::Name) -> Highlight {
291 let default = HighlightTag::Function.into();
293 let parent = match name.syntax().parent() {
298 match parent.kind() {
299 STRUCT_DEF => HighlightTag::Struct.into(),
300 ENUM_DEF => HighlightTag::Enum.into(),
301 UNION_DEF => HighlightTag::Union.into(),
302 TRAIT_DEF => HighlightTag::Trait.into(),
303 TYPE_ALIAS_DEF => HighlightTag::TypeAlias.into(),
304 TYPE_PARAM => HighlightTag::TypeParam.into(),
305 RECORD_FIELD_DEF => HighlightTag::Field.into(),
310 fn highlight_injection(
311 acc: &mut Vec<HighlightedRange>,
312 sema: &Semantics<RootDatabase>,
313 literal: ast::RawString,
314 expanded: SyntaxToken,
316 let call_info = call_info_for_token(&sema, expanded)?;
317 let idx = call_info.active_parameter?;
318 let name = call_info.signature.parameter_names.get(idx)?;
319 if name != "ra_fixture" {
322 let value = literal.value()?;
323 let (analysis, tmp_file_id) = Analysis::from_single_file(value);
325 if let Some(range) = literal.open_quote_text_range() {
326 acc.push(HighlightedRange {
328 highlight: HighlightTag::StringLiteral.into(),
333 for mut h in analysis.highlight(tmp_file_id).unwrap() {
334 if let Some(r) = literal.map_range_up(h.range) {
340 if let Some(range) = literal.close_quote_text_range() {
341 acc.push(HighlightedRange {
343 highlight: HighlightTag::StringLiteral.into(),