]> git.lizzy.rs Git - rust.git/blob - crates/ra_ide/src/syntax_highlighting.rs
eb3dd177935368ede8d56ea27dc9f7870dab7d5a
[rust.git] / crates / ra_ide / src / syntax_highlighting.rs
1 //! FIXME: write short doc here
2
3 use rustc_hash::{FxHashMap, FxHashSet};
4
5 use hir::{InFile, Name};
6 use ra_db::SourceDatabase;
7 use ra_prof::profile;
8 use ra_syntax::{ast, AstNode, Direction, SyntaxElement, SyntaxKind, SyntaxKind::*, TextRange, T};
9
10 use crate::{
11     db::RootDatabase,
12     references::{
13         classify_name, classify_name_ref,
14         NameKind::{self, *},
15     },
16     FileId,
17 };
18
19 pub mod tags {
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";
29
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";
34
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";
41
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";
45 }
46
47 #[derive(Debug)]
48 pub struct HighlightedRange {
49     pub range: TextRange,
50     pub tag: &'static str,
51     pub binding_hash: Option<u64>,
52 }
53
54 fn is_control_keyword(kind: SyntaxKind) -> bool {
55     match kind {
56         T![for]
57         | T![loop]
58         | T![while]
59         | T![continue]
60         | T![break]
61         | T![if]
62         | T![else]
63         | T![match]
64         | T![return] => true,
65         _ => false,
66     }
67 }
68
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();
73
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};
77
78             let mut hasher = DefaultHasher::new();
79             x.hash(&mut hasher);
80             hasher.finish()
81         }
82
83         hash((file_id, name, shadow_count))
84     }
85
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();
90
91     let mut res = Vec::new();
92     for node in root.descendants_with_tokens() {
93         if highlighted.contains(&node) {
94             continue;
95         }
96         let mut binding_hash = None;
97         let tag = match node.kind() {
98             FN_DEF => {
99                 bindings_shadow_count.clear();
100                 continue;
101             }
102             COMMENT => tags::LITERAL_COMMENT,
103             STRING | RAW_STRING | RAW_BYTE_STRING | BYTE_STRING => tags::LITERAL_STRING,
104             ATTR => tags::LITERAL_ATTRIBUTE,
105             NAME_REF => {
106                 if node.ancestors().any(|it| it.kind() == ATTR) {
107                     continue;
108                 }
109
110                 let name_ref = node.as_node().cloned().and_then(ast::NameRef::cast).unwrap();
111                 let name_kind =
112                     classify_name_ref(db, InFile::new(file_id.into(), &name_ref)).map(|d| d.kind);
113
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))
118                     }
119                 };
120
121                 name_kind.map_or(tags::TEXT, |it| highlight_name(db, it))
122             }
123             NAME => {
124                 let name = node.as_node().cloned().and_then(ast::Name::cast).unwrap();
125                 let name_kind =
126                     classify_name(db, InFile::new(file_id.into(), &name)).map(|d| d.kind);
127
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();
131                         *shadow_count += 1;
132                         binding_hash = Some(calc_binding_hash(file_id, &name, *shadow_count))
133                     }
134                 };
135
136                 match name_kind {
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,
142                         _ => tags::FUNCTION,
143                     }),
144                 }
145             }
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,
153             _ => {
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(),
164                                         _ => (),
165                                     }
166                                 }
167                                 res.push(HighlightedRange {
168                                     range: TextRange::from_to(range_start, range_end),
169                                     tag: tags::MACRO,
170                                     binding_hash: None,
171                                 })
172                             }
173                         }
174                     }
175                 }
176                 continue;
177             }
178         };
179         res.push(HighlightedRange { range: node.text_range(), tag, binding_hash })
180     }
181     res
182 }
183
184 pub(crate) fn highlight_as_html(db: &RootDatabase, file_id: FileId, rainbow: bool) -> String {
185     let parse = db.parse(file_id);
186
187     fn rainbowify(seed: u64) -> String {
188         use rand::prelude::*;
189         let mut rng = SmallRng::seed_from_u64(seed);
190         format!(
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),
195         )
196     }
197
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();
203
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);
213                 frontier += 1;
214             } else {
215                 break;
216             }
217         }
218         let text = html_escape(&token.text());
219         let ranges = could_intersect
220             .iter()
221             .filter(|it| token.text_range().is_subrange(&it.range))
222             .collect::<Vec<_>>();
223         if ranges.is_empty() {
224             buf.push_str(&text);
225         } else {
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: {};\"",
231                     hash,
232                     rainbowify(hash)
233                 ),
234                 _ => "".into(),
235             };
236             buf.push_str(&format!("<span class=\"{}\"{}>{}</span>", classes, color, text));
237         }
238     }
239     buf.push_str("</code></pre>");
240     buf
241 }
242
243 fn highlight_name(db: &RootDatabase, name_kind: NameKind) -> &'static str {
244     match name_kind {
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,
261         Local(local) => {
262             if local.is_mut(db) {
263                 tags::VARIABLE_MUT
264             } else if local.ty(db).is_mutable_reference() {
265                 tags::VARIABLE_MUT
266             } else {
267                 tags::VARIABLE
268             }
269         }
270     }
271 }
272
273 //FIXME: like, real html escaping
274 fn html_escape(text: &str) -> String {
275     text.replace("<", "&lt;").replace(">", "&gt;")
276 }
277
278 const STYLE: &str = "
279 <style>
280 body                { margin: 0; }
281 pre                 { color: #DCDCCC; background: #3F3F3F; font-size: 22px; padding: 0.4em; }
282
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; }
297
298 .keyword            { color: #F0DFAF; }
299 .keyword\\.unsafe   { color: #DFAF8F; }
300 .keyword\\.control  { color: #F0DFAF; font-weight: bold; }
301 </style>
302 ";
303
304 #[cfg(test)]
305 mod tests {
306     use crate::mock_analysis::single_file;
307     use test_utils::{assert_eq_text, project_dir, read_text};
308
309     #[test]
310     fn test_highlighting() {
311         let (analysis, file_id) = single_file(
312             r#"
313 #[derive(Clone, Debug)]
314 struct Foo {
315     pub x: i32,
316     pub y: i32,
317 }
318
319 fn foo<T>() -> T {
320     unimplemented!();
321     foo::<i32>();
322 }
323
324 // comment
325 fn main() {
326     println!("Hello, {}!", 92);
327
328     let mut vec = Vec::new();
329     if true {
330         vec.push(Foo { x: 0, y: 1 });
331     }
332     unsafe { vec.set_len(0); }
333
334     let mut x = 42;
335     let y = &mut x;
336     let z = &y;
337
338     y;
339 }
340
341 enum E<X> {
342     V(X)
343 }
344
345 impl<X> E<X> {
346     fn new<T>() -> E<T> {}
347 }
348 "#
349             .trim(),
350         );
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);
356     }
357
358     #[test]
359     fn test_rainbow_highlighting() {
360         let (analysis, file_id) = single_file(
361             r#"
362 fn main() {
363     let hello = "hello";
364     let x = hello.to_string();
365     let y = hello.to_string();
366
367     let x = "other color please!";
368     let y = x.to_string();
369 }
370
371 fn bar() {
372     let mut hello = "hello";
373 }
374 "#
375             .trim(),
376         );
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);
382     }
383 }