1 //! FIXME: write short doc here
3 use rustc_hash::{FxHashMap, FxHashSet};
5 use hir::{InFile, Name};
6 use ra_db::SourceDatabase;
8 use ra_syntax::{ast, AstNode, Direction, SyntaxElement, SyntaxKind, SyntaxKind::*, TextRange, T};
13 classify_name, classify_name_ref,
20 pub struct HighlightedRange {
22 pub tag: &'static str,
23 pub binding_hash: Option<u64>,
26 fn is_control_keyword(kind: SyntaxKind) -> bool {
41 pub(crate) fn highlight(db: &RootDatabase, file_id: FileId) -> Vec<HighlightedRange> {
42 let _p = profile("highlight");
43 let parse = db.parse(file_id);
44 let root = parse.tree().syntax().clone();
46 fn calc_binding_hash(file_id: FileId, name: &Name, shadow_count: u32) -> u64 {
47 fn hash<T: std::hash::Hash + std::fmt::Debug>(x: T) -> u64 {
48 use std::{collections::hash_map::DefaultHasher, hash::Hasher};
50 let mut hasher = DefaultHasher::new();
55 hash((file_id, name, shadow_count))
58 // Visited nodes to handle highlighting priorities
59 // FIXME: retain only ranges here
60 let mut highlighted: FxHashSet<SyntaxElement> = FxHashSet::default();
61 let mut bindings_shadow_count: FxHashMap<Name, u32> = FxHashMap::default();
63 let mut res = Vec::new();
64 for node in root.descendants_with_tokens() {
65 if highlighted.contains(&node) {
68 let mut binding_hash = None;
69 let tag = match node.kind() {
71 bindings_shadow_count.clear();
75 STRING | RAW_STRING | RAW_BYTE_STRING | BYTE_STRING => "string",
78 if node.ancestors().any(|it| it.kind() == ATTR) {
82 let name_ref = node.as_node().cloned().and_then(ast::NameRef::cast).unwrap();
84 classify_name_ref(db, InFile::new(file_id.into(), &name_ref)).map(|d| d.kind);
86 if let Some(Local(local)) = &name_kind {
87 if let Some(name) = local.name(db) {
88 let shadow_count = bindings_shadow_count.entry(name.clone()).or_default();
89 binding_hash = Some(calc_binding_hash(file_id, &name, *shadow_count))
93 name_kind.map_or("text", |it| highlight_name(db, it))
96 let name = node.as_node().cloned().and_then(ast::Name::cast).unwrap();
98 classify_name(db, InFile::new(file_id.into(), &name)).map(|d| d.kind);
100 if let Some(Local(local)) = &name_kind {
101 if let Some(name) = local.name(db) {
102 let shadow_count = bindings_shadow_count.entry(name.clone()).or_default();
104 binding_hash = Some(calc_binding_hash(file_id, &name, *shadow_count))
109 Some(name_kind) => highlight_name(db, name_kind),
110 None => name.syntax().parent().map_or("function", |x| match x.kind() {
111 STRUCT_DEF | ENUM_DEF | TRAIT_DEF | TYPE_ALIAS_DEF => "type",
112 TYPE_PARAM => "type.param",
113 RECORD_FIELD_DEF => "field",
118 INT_NUMBER | FLOAT_NUMBER => "literal.numeric",
119 BYTE => "literal.byte",
120 CHAR => "literal.char",
121 LIFETIME => "type.lifetime",
122 T![unsafe] => "keyword.unsafe",
123 k if is_control_keyword(k) => "keyword.control",
124 k if k.is_keyword() => "keyword",
126 if let Some(macro_call) = node.as_node().cloned().and_then(ast::MacroCall::cast) {
127 if let Some(path) = macro_call.path() {
128 if let Some(segment) = path.segment() {
129 if let Some(name_ref) = segment.name_ref() {
130 highlighted.insert(name_ref.syntax().clone().into());
131 let range_start = name_ref.syntax().text_range().start();
132 let mut range_end = name_ref.syntax().text_range().end();
133 for sibling in path.syntax().siblings_with_tokens(Direction::Next) {
134 match sibling.kind() {
135 T![!] | IDENT => range_end = sibling.text_range().end(),
139 res.push(HighlightedRange {
140 range: TextRange::from_to(range_start, range_end),
151 res.push(HighlightedRange { range: node.text_range(), tag, binding_hash })
156 pub(crate) fn highlight_as_html(db: &RootDatabase, file_id: FileId, rainbow: bool) -> String {
157 let parse = db.parse(file_id);
159 fn rainbowify(seed: u64) -> String {
160 use rand::prelude::*;
161 let mut rng = SmallRng::seed_from_u64(seed);
163 "hsl({h},{s}%,{l}%)",
164 h = rng.gen_range::<u16, _, _>(0, 361),
165 s = rng.gen_range::<u16, _, _>(42, 99),
166 l = rng.gen_range::<u16, _, _>(40, 91),
170 let mut ranges = highlight(db, file_id);
171 ranges.sort_by_key(|it| it.range.start());
172 // quick non-optimal heuristic to intersect token ranges and highlighted ranges
173 let mut frontier = 0;
174 let mut could_intersect: Vec<&HighlightedRange> = Vec::new();
176 let mut buf = String::new();
177 buf.push_str(&STYLE);
178 buf.push_str("<pre><code>");
179 let tokens = parse.tree().syntax().descendants_with_tokens().filter_map(|it| it.into_token());
180 for token in tokens {
181 could_intersect.retain(|it| token.text_range().start() <= it.range.end());
182 while let Some(r) = ranges.get(frontier) {
183 if r.range.start() <= token.text_range().end() {
184 could_intersect.push(r);
190 let text = html_escape(&token.text());
191 let ranges = could_intersect
193 .filter(|it| token.text_range().is_subrange(&it.range))
194 .collect::<Vec<_>>();
195 if ranges.is_empty() {
198 let classes = ranges.iter().map(|x| x.tag).collect::<Vec<_>>().join(" ");
199 let binding_hash = ranges.first().and_then(|x| x.binding_hash);
200 let color = match (rainbow, binding_hash) {
201 (true, Some(hash)) => format!(
202 " data-binding-hash=\"{}\" style=\"color: {};\"",
208 buf.push_str(&format!("<span class=\"{}\"{}>{}</span>", classes, color, text));
211 buf.push_str("</code></pre>");
215 fn highlight_name(db: &RootDatabase, name_kind: NameKind) -> &'static str {
219 AssocItem(hir::AssocItem::Function(_)) => "function",
220 AssocItem(hir::AssocItem::Const(_)) => "constant",
221 AssocItem(hir::AssocItem::TypeAlias(_)) => "type",
222 Def(hir::ModuleDef::Module(_)) => "module",
223 Def(hir::ModuleDef::Function(_)) => "function",
224 Def(hir::ModuleDef::Adt(_)) => "type",
225 Def(hir::ModuleDef::EnumVariant(_)) => "constant",
226 Def(hir::ModuleDef::Const(_)) => "constant",
227 Def(hir::ModuleDef::Static(_)) => "constant",
228 Def(hir::ModuleDef::Trait(_)) => "type",
229 Def(hir::ModuleDef::TypeAlias(_)) => "type",
230 Def(hir::ModuleDef::BuiltinType(_)) => "type.builtin",
231 SelfType(_) => "type.self",
232 TypeParam(_) => "type.param",
234 if local.is_mut(db) {
236 } else if local.ty(db).is_mutable_reference() {
245 //FIXME: like, real html escaping
246 fn html_escape(text: &str) -> String {
247 text.replace("<", "<").replace(">", ">")
250 const STYLE: &str = "
253 pre { color: #DCDCCC; background: #3F3F3F; font-size: 22px; padding: 0.4em; }
255 .comment { color: #7F9F7F; }
256 .string { color: #CC9393; }
257 .function { color: #93E0E3; }
258 .parameter { color: #94BFF3; }
259 .builtin { color: #DD6718; }
260 .text { color: #DCDCCC; }
261 .type { color: #7CB8BB; }
262 .type\\.param { color: #20999D; }
263 .attribute { color: #94BFF3; }
264 .literal { color: #BFEBBF; }
265 .literal\\.numeric { color: #6A8759; }
266 .macro { color: #94BFF3; }
267 .variable { color: #DCDCCC; }
268 .variable\\.mut { color: #DCDCCC; text-decoration: underline; }
270 .keyword { color: #F0DFAF; }
271 .keyword\\.unsafe { color: #DFAF8F; }
272 .keyword\\.control { color: #F0DFAF; font-weight: bold; }
278 use crate::mock_analysis::single_file;
279 use test_utils::{assert_eq_text, project_dir, read_text};
282 fn test_highlighting() {
283 let (analysis, file_id) = single_file(
285 #[derive(Clone, Debug)]
298 println!("Hello, {}!", 92);
300 let mut vec = Vec::new();
302 vec.push(Foo { x: 0, y: 1 });
304 unsafe { vec.set_len(0); }
318 fn new<T>() -> E<T> {}
323 let dst_file = project_dir().join("crates/ra_ide/src/snapshots/highlighting.html");
324 let actual_html = &analysis.highlight_as_html(file_id, false).unwrap();
325 let expected_html = &read_text(&dst_file);
326 std::fs::write(dst_file, &actual_html).unwrap();
327 assert_eq_text!(expected_html, actual_html);
331 fn test_rainbow_highlighting() {
332 let (analysis, file_id) = single_file(
336 let x = hello.to_string();
337 let y = hello.to_string();
339 let x = "other color please!";
340 let y = x.to_string();
344 let mut hello = "hello";
349 let dst_file = project_dir().join("crates/ra_ide/src/snapshots/rainbow_highlighting.html");
350 let actual_html = &analysis.highlight_as_html(file_id, true).unwrap();
351 let expected_html = &read_text(&dst_file);
352 std::fs::write(dst_file, &actual_html).unwrap();
353 assert_eq_text!(expected_html, actual_html);