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(crate) const FIELD: &'static str = "field";
21 pub(crate) const FUNCTION: &'static str = "function";
22 pub(crate) const MODULE: &'static str = "module";
23 pub(crate) const TYPE: &'static str = "type";
24 pub(crate) const CONSTANT: &'static str = "constant";
25 pub(crate) const MACRO: &'static str = "macro";
26 pub(crate) const VARIABLE: &'static str = "variable";
27 pub(crate) const VARIABLE_MUT: &'static str = "variable.mut";
28 pub(crate) const TEXT: &'static str = "text";
30 pub(crate) const TYPE_BUILTIN: &'static str = "type.builtin";
31 pub(crate) const TYPE_SELF: &'static str = "type.self";
32 pub(crate) const TYPE_PARAM: &'static str = "type.param";
33 pub(crate) const TYPE_LIFETIME: &'static str = "type.lifetime";
35 pub(crate) const LITERAL_BYTE: &'static str = "literal.byte";
36 pub(crate) const LITERAL_NUMERIC: &'static str = "literal.numeric";
37 pub(crate) const LITERAL_CHAR: &'static str = "literal.char";
38 pub(crate) const LITERAL_COMMENT: &'static str = "comment";
39 pub(crate) const LITERAL_STRING: &'static str = "string";
40 pub(crate) const LITERAL_ATTRIBUTE: &'static str = "attribute";
42 pub(crate) const KEYWORD_UNSAFE: &'static str = "keyword.unsafe";
43 pub(crate) const KEYWORD_CONTROL: &'static str = "keyword.control";
44 pub(crate) const KEYWORD: &'static str = "keyword";
48 pub struct HighlightedRange {
50 pub tag: &'static str,
51 pub binding_hash: Option<u64>,
54 fn is_control_keyword(kind: SyntaxKind) -> bool {
69 pub(crate) fn highlight(db: &RootDatabase, file_id: FileId) -> Vec<HighlightedRange> {
70 let _p = profile("highlight");
71 let parse = db.parse(file_id);
72 let root = parse.tree().syntax().clone();
74 fn calc_binding_hash(file_id: FileId, name: &Name, shadow_count: u32) -> u64 {
75 fn hash<T: std::hash::Hash + std::fmt::Debug>(x: T) -> u64 {
76 use std::{collections::hash_map::DefaultHasher, hash::Hasher};
78 let mut hasher = DefaultHasher::new();
83 hash((file_id, name, shadow_count))
86 // Visited nodes to handle highlighting priorities
87 // FIXME: retain only ranges here
88 let mut highlighted: FxHashSet<SyntaxElement> = FxHashSet::default();
89 let mut bindings_shadow_count: FxHashMap<Name, u32> = FxHashMap::default();
91 let mut res = Vec::new();
92 for node in root.descendants_with_tokens() {
93 if highlighted.contains(&node) {
96 let mut binding_hash = None;
97 let tag = match node.kind() {
99 bindings_shadow_count.clear();
102 COMMENT => tags::LITERAL_COMMENT,
103 STRING | RAW_STRING | RAW_BYTE_STRING | BYTE_STRING => tags::LITERAL_STRING,
104 ATTR => tags::LITERAL_ATTRIBUTE,
106 if node.ancestors().any(|it| it.kind() == ATTR) {
110 let name_ref = node.as_node().cloned().and_then(ast::NameRef::cast).unwrap();
112 classify_name_ref(db, InFile::new(file_id.into(), &name_ref)).map(|d| d.kind);
114 if let Some(Local(local)) = &name_kind {
115 if let Some(name) = local.name(db) {
116 let shadow_count = bindings_shadow_count.entry(name.clone()).or_default();
117 binding_hash = Some(calc_binding_hash(file_id, &name, *shadow_count))
121 name_kind.map_or(tags::TEXT, |it| highlight_name(db, it))
124 let name = node.as_node().cloned().and_then(ast::Name::cast).unwrap();
126 classify_name(db, InFile::new(file_id.into(), &name)).map(|d| d.kind);
128 if let Some(Local(local)) = &name_kind {
129 if let Some(name) = local.name(db) {
130 let shadow_count = bindings_shadow_count.entry(name.clone()).or_default();
132 binding_hash = Some(calc_binding_hash(file_id, &name, *shadow_count))
137 Some(name_kind) => highlight_name(db, name_kind),
138 None => name.syntax().parent().map_or(tags::FUNCTION, |x| match x.kind() {
139 STRUCT_DEF | ENUM_DEF | TRAIT_DEF | TYPE_ALIAS_DEF => tags::TYPE,
140 TYPE_PARAM => tags::TYPE_PARAM,
141 RECORD_FIELD_DEF => tags::FIELD,
146 INT_NUMBER | FLOAT_NUMBER => tags::LITERAL_NUMERIC,
147 BYTE => tags::LITERAL_BYTE,
148 CHAR => tags::LITERAL_CHAR,
149 LIFETIME => tags::TYPE_LIFETIME,
150 T![unsafe] => tags::KEYWORD_UNSAFE,
151 k if is_control_keyword(k) => tags::KEYWORD_CONTROL,
152 k if k.is_keyword() => tags::KEYWORD,
154 if let Some(macro_call) = node.as_node().cloned().and_then(ast::MacroCall::cast) {
155 if let Some(path) = macro_call.path() {
156 if let Some(segment) = path.segment() {
157 if let Some(name_ref) = segment.name_ref() {
158 highlighted.insert(name_ref.syntax().clone().into());
159 let range_start = name_ref.syntax().text_range().start();
160 let mut range_end = name_ref.syntax().text_range().end();
161 for sibling in path.syntax().siblings_with_tokens(Direction::Next) {
162 match sibling.kind() {
163 T![!] | IDENT => range_end = sibling.text_range().end(),
167 res.push(HighlightedRange {
168 range: TextRange::from_to(range_start, range_end),
179 res.push(HighlightedRange { range: node.text_range(), tag, binding_hash })
184 pub(crate) fn highlight_as_html(db: &RootDatabase, file_id: FileId, rainbow: bool) -> String {
185 let parse = db.parse(file_id);
187 fn rainbowify(seed: u64) -> String {
188 use rand::prelude::*;
189 let mut rng = SmallRng::seed_from_u64(seed);
191 "hsl({h},{s}%,{l}%)",
192 h = rng.gen_range::<u16, _, _>(0, 361),
193 s = rng.gen_range::<u16, _, _>(42, 99),
194 l = rng.gen_range::<u16, _, _>(40, 91),
198 let mut ranges = highlight(db, file_id);
199 ranges.sort_by_key(|it| it.range.start());
200 // quick non-optimal heuristic to intersect token ranges and highlighted ranges
201 let mut frontier = 0;
202 let mut could_intersect: Vec<&HighlightedRange> = Vec::new();
204 let mut buf = String::new();
205 buf.push_str(&STYLE);
206 buf.push_str("<pre><code>");
207 let tokens = parse.tree().syntax().descendants_with_tokens().filter_map(|it| it.into_token());
208 for token in tokens {
209 could_intersect.retain(|it| token.text_range().start() <= it.range.end());
210 while let Some(r) = ranges.get(frontier) {
211 if r.range.start() <= token.text_range().end() {
212 could_intersect.push(r);
218 let text = html_escape(&token.text());
219 let ranges = could_intersect
221 .filter(|it| token.text_range().is_subrange(&it.range))
222 .collect::<Vec<_>>();
223 if ranges.is_empty() {
226 let classes = ranges.iter().map(|x| x.tag).collect::<Vec<_>>().join(" ");
227 let binding_hash = ranges.first().and_then(|x| x.binding_hash);
228 let color = match (rainbow, binding_hash) {
229 (true, Some(hash)) => format!(
230 " data-binding-hash=\"{}\" style=\"color: {};\"",
236 buf.push_str(&format!("<span class=\"{}\"{}>{}</span>", classes, color, text));
239 buf.push_str("</code></pre>");
243 fn highlight_name(db: &RootDatabase, name_kind: NameKind) -> &'static str {
245 Macro(_) => tags::MACRO,
246 Field(_) => tags::FIELD,
247 AssocItem(hir::AssocItem::Function(_)) => tags::FUNCTION,
248 AssocItem(hir::AssocItem::Const(_)) => tags::CONSTANT,
249 AssocItem(hir::AssocItem::TypeAlias(_)) => tags::TYPE,
250 Def(hir::ModuleDef::Module(_)) => tags::MODULE,
251 Def(hir::ModuleDef::Function(_)) => tags::FUNCTION,
252 Def(hir::ModuleDef::Adt(_)) => tags::TYPE,
253 Def(hir::ModuleDef::EnumVariant(_)) => tags::CONSTANT,
254 Def(hir::ModuleDef::Const(_)) => tags::CONSTANT,
255 Def(hir::ModuleDef::Static(_)) => tags::CONSTANT,
256 Def(hir::ModuleDef::Trait(_)) => tags::TYPE,
257 Def(hir::ModuleDef::TypeAlias(_)) => tags::TYPE,
258 Def(hir::ModuleDef::BuiltinType(_)) => tags::TYPE_BUILTIN,
259 SelfType(_) => tags::TYPE_SELF,
260 TypeParam(_) => tags::TYPE_PARAM,
262 if local.is_mut(db) {
264 } else if local.ty(db).is_mutable_reference() {
273 //FIXME: like, real html escaping
274 fn html_escape(text: &str) -> String {
275 text.replace("<", "<").replace(">", ">")
278 const STYLE: &str = "
281 pre { color: #DCDCCC; background: #3F3F3F; font-size: 22px; padding: 0.4em; }
283 .comment { color: #7F9F7F; }
284 .string { color: #CC9393; }
285 .function { color: #93E0E3; }
286 .parameter { color: #94BFF3; }
287 .builtin { color: #DD6718; }
288 .text { color: #DCDCCC; }
289 .type { color: #7CB8BB; }
290 .type\\.param { color: #20999D; }
291 .attribute { color: #94BFF3; }
292 .literal { color: #BFEBBF; }
293 .literal\\.numeric { color: #6A8759; }
294 .macro { color: #94BFF3; }
295 .variable { color: #DCDCCC; }
296 .variable\\.mut { color: #DCDCCC; text-decoration: underline; }
298 .keyword { color: #F0DFAF; }
299 .keyword\\.unsafe { color: #DFAF8F; }
300 .keyword\\.control { color: #F0DFAF; font-weight: bold; }
306 use crate::mock_analysis::single_file;
307 use test_utils::{assert_eq_text, project_dir, read_text};
310 fn test_highlighting() {
311 let (analysis, file_id) = single_file(
313 #[derive(Clone, Debug)]
326 println!("Hello, {}!", 92);
328 let mut vec = Vec::new();
330 vec.push(Foo { x: 0, y: 1 });
332 unsafe { vec.set_len(0); }
346 fn new<T>() -> E<T> {}
351 let dst_file = project_dir().join("crates/ra_ide/src/snapshots/highlighting.html");
352 let actual_html = &analysis.highlight_as_html(file_id, false).unwrap();
353 let expected_html = &read_text(&dst_file);
354 std::fs::write(dst_file, &actual_html).unwrap();
355 assert_eq_text!(expected_html, actual_html);
359 fn test_rainbow_highlighting() {
360 let (analysis, file_id) = single_file(
364 let x = hello.to_string();
365 let y = hello.to_string();
367 let x = "other color please!";
368 let y = x.to_string();
372 let mut hello = "hello";
377 let dst_file = project_dir().join("crates/ra_ide/src/snapshots/rainbow_highlighting.html");
378 let actual_html = &analysis.highlight_as_html(file_id, true).unwrap();
379 let expected_html = &read_text(&dst_file);
380 std::fs::write(dst_file, &actual_html).unwrap();
381 assert_eq_text!(expected_html, actual_html);