]> git.lizzy.rs Git - rust.git/blob - crates/ra_ide/src/syntax_highlighting.rs
Syntactic highlighting of NAME_REF for injections
[rust.git] / crates / ra_ide / src / syntax_highlighting.rs
1 mod tags;
2 mod html;
3 mod injection;
4 #[cfg(test)]
5 mod tests;
6
7 use hir::{Name, Semantics};
8 use ra_ide_db::{
9     defs::{classify_name, classify_name_ref, Definition, NameClass, NameRefClass},
10     RootDatabase,
11 };
12 use ra_prof::profile;
13 use ra_syntax::{
14     ast::{self, HasFormatSpecifier},
15     AstNode, AstToken, Direction, NodeOrToken, SyntaxElement,
16     SyntaxKind::*,
17     TextRange, WalkEvent, T,
18 };
19 use rustc_hash::FxHashMap;
20
21 use crate::FileId;
22
23 use ast::FormatSpecifier;
24 pub(crate) use html::highlight_as_html;
25 pub use tags::{Highlight, HighlightModifier, HighlightModifiers, HighlightTag};
26
27 #[derive(Debug, Clone)]
28 pub struct HighlightedRange {
29     pub range: TextRange,
30     pub highlight: Highlight,
31     pub binding_hash: Option<u64>,
32 }
33
34 // Feature: Semantic Syntax Highlighting
35 //
36 // rust-analyzer highlights the code semantically.
37 // For example, `bar` in `foo::Bar` might be colored differently depending on whether `Bar` is an enum or a trait.
38 // rust-analyzer does not specify colors directly, instead it assigns tag (like `struct`) and a set of modifiers (like `declaration`) to each token.
39 // It's up to the client to map those to specific colors.
40 //
41 // The general rule is that a reference to an entity gets colored the same way as the entity itself.
42 // We also give special modifier for `mut` and `&mut` local variables.
43 pub(crate) fn highlight(
44     db: &RootDatabase,
45     file_id: FileId,
46     range_to_highlight: Option<TextRange>,
47     syntactic_name_ref_highlighting: bool,
48 ) -> Vec<HighlightedRange> {
49     let _p = profile("highlight");
50     let sema = Semantics::new(db);
51
52     // Determine the root based on the given range.
53     let (root, range_to_highlight) = {
54         let source_file = sema.parse(file_id);
55         match range_to_highlight {
56             Some(range) => {
57                 let node = match source_file.syntax().covering_element(range) {
58                     NodeOrToken::Node(it) => it,
59                     NodeOrToken::Token(it) => it.parent(),
60                 };
61                 (node, range)
62             }
63             None => (source_file.syntax().clone(), source_file.syntax().text_range()),
64         }
65     };
66
67     let mut bindings_shadow_count: FxHashMap<Name, u32> = FxHashMap::default();
68     // We use a stack for the DFS traversal below.
69     // When we leave a node, the we use it to flatten the highlighted ranges.
70     let mut stack = HighlightedRangeStack::new();
71
72     let mut current_macro_call: Option<ast::MacroCall> = None;
73     let mut format_string: Option<SyntaxElement> = None;
74
75     // Walk all nodes, keeping track of whether we are inside a macro or not.
76     // If in macro, expand it first and highlight the expanded code.
77     for event in root.preorder_with_tokens() {
78         match &event {
79             WalkEvent::Enter(_) => stack.push(),
80             WalkEvent::Leave(_) => stack.pop(),
81         };
82
83         let event_range = match &event {
84             WalkEvent::Enter(it) => it.text_range(),
85             WalkEvent::Leave(it) => it.text_range(),
86         };
87
88         // Element outside of the viewport, no need to highlight
89         if range_to_highlight.intersect(event_range).is_none() {
90             continue;
91         }
92
93         // Track "inside macro" state
94         match event.clone().map(|it| it.into_node().and_then(ast::MacroCall::cast)) {
95             WalkEvent::Enter(Some(mc)) => {
96                 current_macro_call = Some(mc.clone());
97                 if let Some(range) = macro_call_range(&mc) {
98                     stack.add(HighlightedRange {
99                         range,
100                         highlight: HighlightTag::Macro.into(),
101                         binding_hash: None,
102                     });
103                 }
104                 if let Some(name) = mc.is_macro_rules() {
105                     if let Some((highlight, binding_hash)) = highlight_element(
106                         &sema,
107                         &mut bindings_shadow_count,
108                         syntactic_name_ref_highlighting,
109                         name.syntax().clone().into(),
110                     ) {
111                         stack.add(HighlightedRange {
112                             range: name.syntax().text_range(),
113                             highlight,
114                             binding_hash,
115                         });
116                     }
117                 }
118                 continue;
119             }
120             WalkEvent::Leave(Some(mc)) => {
121                 assert!(current_macro_call == Some(mc));
122                 current_macro_call = None;
123                 format_string = None;
124                 continue;
125             }
126             _ => (),
127         }
128
129         // Check for Rust code in documentation
130         match &event {
131             WalkEvent::Leave(NodeOrToken::Node(node)) => {
132                 if let Some((doctest, range_mapping, new_comments)) =
133                     injection::extract_doc_comments(node)
134                 {
135                     injection::highlight_doc_comment(
136                         doctest,
137                         range_mapping,
138                         new_comments,
139                         &mut stack,
140                     );
141                 }
142             }
143             _ => (),
144         }
145
146         let element = match event {
147             WalkEvent::Enter(it) => it,
148             WalkEvent::Leave(_) => continue,
149         };
150
151         let range = element.text_range();
152
153         let element_to_highlight = if current_macro_call.is_some() {
154             // Inside a macro -- expand it first
155             let token = match element.clone().into_token() {
156                 Some(it) if it.parent().kind() == TOKEN_TREE => it,
157                 _ => continue,
158             };
159             let token = sema.descend_into_macros(token.clone());
160             let parent = token.parent();
161
162             // Check if macro takes a format string and remember it for highlighting later.
163             // The macros that accept a format string expand to a compiler builtin macros
164             // `format_args` and `format_args_nl`.
165             if let Some(name) = parent
166                 .parent()
167                 .and_then(ast::MacroCall::cast)
168                 .and_then(|mc| mc.path())
169                 .and_then(|p| p.segment())
170                 .and_then(|s| s.name_ref())
171             {
172                 match name.text().as_str() {
173                     "format_args" | "format_args_nl" => {
174                         format_string = parent
175                             .children_with_tokens()
176                             .filter(|t| t.kind() != WHITESPACE)
177                             .nth(1)
178                             .filter(|e| {
179                                 ast::String::can_cast(e.kind())
180                                     || ast::RawString::can_cast(e.kind())
181                             })
182                     }
183                     _ => {}
184                 }
185             }
186
187             // We only care Name and Name_ref
188             match (token.kind(), parent.kind()) {
189                 (IDENT, NAME) | (IDENT, NAME_REF) => parent.into(),
190                 _ => token.into(),
191             }
192         } else {
193             element.clone()
194         };
195
196         if let Some(token) = element.as_token().cloned().and_then(ast::RawString::cast) {
197             let expanded = element_to_highlight.as_token().unwrap().clone();
198             if injection::highlight_injection(&mut stack, &sema, token, expanded).is_some() {
199                 continue;
200             }
201         }
202
203         let is_format_string = format_string.as_ref() == Some(&element_to_highlight);
204
205         if let Some((highlight, binding_hash)) = highlight_element(
206             &sema,
207             &mut bindings_shadow_count,
208             syntactic_name_ref_highlighting,
209             element_to_highlight.clone(),
210         ) {
211             stack.add(HighlightedRange { range, highlight, binding_hash });
212             if let Some(string) =
213                 element_to_highlight.as_token().cloned().and_then(ast::String::cast)
214             {
215                 stack.push();
216                 if is_format_string {
217                     string.lex_format_specifier(|piece_range, kind| {
218                         if let Some(highlight) = highlight_format_specifier(kind) {
219                             stack.add(HighlightedRange {
220                                 range: piece_range + range.start(),
221                                 highlight: highlight.into(),
222                                 binding_hash: None,
223                             });
224                         }
225                     });
226                 }
227                 stack.pop();
228             } else if let Some(string) =
229                 element_to_highlight.as_token().cloned().and_then(ast::RawString::cast)
230             {
231                 stack.push();
232                 if is_format_string {
233                     string.lex_format_specifier(|piece_range, kind| {
234                         if let Some(highlight) = highlight_format_specifier(kind) {
235                             stack.add(HighlightedRange {
236                                 range: piece_range + range.start(),
237                                 highlight: highlight.into(),
238                                 binding_hash: None,
239                             });
240                         }
241                     });
242                 }
243                 stack.pop();
244             }
245         }
246     }
247
248     stack.flattened()
249 }
250
251 #[derive(Debug)]
252 struct HighlightedRangeStack {
253     stack: Vec<Vec<HighlightedRange>>,
254 }
255
256 /// We use a stack to implement the flattening logic for the highlighted
257 /// syntax ranges.
258 impl HighlightedRangeStack {
259     fn new() -> Self {
260         Self { stack: vec![Vec::new()] }
261     }
262
263     fn push(&mut self) {
264         self.stack.push(Vec::new());
265     }
266
267     /// Flattens the highlighted ranges.
268     ///
269     /// For example `#[cfg(feature = "foo")]` contains the nested ranges:
270     /// 1) parent-range: Attribute [0, 23)
271     /// 2) child-range: String [16, 21)
272     ///
273     /// The following code implements the flattening, for our example this results to:
274     /// `[Attribute [0, 16), String [16, 21), Attribute [21, 23)]`
275     fn pop(&mut self) {
276         let children = self.stack.pop().unwrap();
277         let prev = self.stack.last_mut().unwrap();
278         let needs_flattening = !children.is_empty()
279             && !prev.is_empty()
280             && prev.last().unwrap().range.contains_range(children.first().unwrap().range);
281         if !needs_flattening {
282             prev.extend(children);
283         } else {
284             let mut parent = prev.pop().unwrap();
285             for ele in children {
286                 assert!(parent.range.contains_range(ele.range));
287
288                 let cloned = Self::intersect(&mut parent, &ele);
289                 if !parent.range.is_empty() {
290                     prev.push(parent);
291                 }
292                 prev.push(ele);
293                 parent = cloned;
294             }
295             if !parent.range.is_empty() {
296                 prev.push(parent);
297             }
298         }
299     }
300
301     /// Intersects the `HighlightedRange` `parent` with `child`.
302     /// `parent` is mutated in place, becoming the range before `child`.
303     /// Returns the range (of the same type as `parent`) *after* `child`.
304     fn intersect(parent: &mut HighlightedRange, child: &HighlightedRange) -> HighlightedRange {
305         assert!(parent.range.contains_range(child.range));
306
307         let mut cloned = parent.clone();
308         parent.range = TextRange::new(parent.range.start(), child.range.start());
309         cloned.range = TextRange::new(child.range.end(), cloned.range.end());
310
311         cloned
312     }
313
314     /// Similar to `pop`, but can modify arbitrary prior ranges (where `pop`)
315     /// can only modify the last range currently on the stack.
316     /// Can be used to do injections that span multiple ranges, like the
317     /// doctest injection below.
318     /// If `delete` is set to true, the parent range is deleted instead of
319     /// intersected.
320     ///
321     /// Note that `pop` can be simulated by `pop_and_inject(false)` but the
322     /// latter is computationally more expensive.
323     fn pop_and_inject(&mut self, delete: bool) {
324         let mut children = self.stack.pop().unwrap();
325         let prev = self.stack.last_mut().unwrap();
326         children.sort_by_key(|range| range.range.start());
327         prev.sort_by_key(|range| range.range.start());
328
329         for child in children {
330             if let Some(idx) =
331                 prev.iter().position(|parent| parent.range.contains_range(child.range))
332             {
333                 let cloned = Self::intersect(&mut prev[idx], &child);
334                 let insert_idx = if delete || prev[idx].range.is_empty() {
335                     prev.remove(idx);
336                     idx
337                 } else {
338                     idx + 1
339                 };
340                 prev.insert(insert_idx, child);
341                 if !delete && !cloned.range.is_empty() {
342                     prev.insert(insert_idx + 1, cloned);
343                 }
344             } else if let Some(_idx) =
345                 prev.iter().position(|parent| parent.range.contains(child.range.start()))
346             {
347                 unreachable!("child range should be completely contained in parent range");
348             } else {
349                 let idx = prev
350                     .binary_search_by_key(&child.range.start(), |range| range.range.start())
351                     .unwrap_or_else(|x| x);
352                 prev.insert(idx, child);
353             }
354         }
355     }
356
357     fn add(&mut self, range: HighlightedRange) {
358         self.stack
359             .last_mut()
360             .expect("during DFS traversal, the stack must not be empty")
361             .push(range)
362     }
363
364     fn flattened(mut self) -> Vec<HighlightedRange> {
365         assert_eq!(
366             self.stack.len(),
367             1,
368             "after DFS traversal, the stack should only contain a single element"
369         );
370         let mut res = self.stack.pop().unwrap();
371         res.sort_by_key(|range| range.range.start());
372         // Check that ranges are sorted and disjoint
373         assert!(res
374             .iter()
375             .zip(res.iter().skip(1))
376             .all(|(left, right)| left.range.end() <= right.range.start()));
377         res
378     }
379 }
380
381 fn highlight_format_specifier(kind: FormatSpecifier) -> Option<HighlightTag> {
382     Some(match kind {
383         FormatSpecifier::Open
384         | FormatSpecifier::Close
385         | FormatSpecifier::Colon
386         | FormatSpecifier::Fill
387         | FormatSpecifier::Align
388         | FormatSpecifier::Sign
389         | FormatSpecifier::NumberSign
390         | FormatSpecifier::DollarSign
391         | FormatSpecifier::Dot
392         | FormatSpecifier::Asterisk
393         | FormatSpecifier::QuestionMark => HighlightTag::FormatSpecifier,
394         FormatSpecifier::Integer | FormatSpecifier::Zero => HighlightTag::NumericLiteral,
395         FormatSpecifier::Identifier => HighlightTag::Local,
396     })
397 }
398
399 fn macro_call_range(macro_call: &ast::MacroCall) -> Option<TextRange> {
400     let path = macro_call.path()?;
401     let name_ref = path.segment()?.name_ref()?;
402
403     let range_start = name_ref.syntax().text_range().start();
404     let mut range_end = name_ref.syntax().text_range().end();
405     for sibling in path.syntax().siblings_with_tokens(Direction::Next) {
406         match sibling.kind() {
407             T![!] | IDENT => range_end = sibling.text_range().end(),
408             _ => (),
409         }
410     }
411
412     Some(TextRange::new(range_start, range_end))
413 }
414
415 fn highlight_element(
416     sema: &Semantics<RootDatabase>,
417     bindings_shadow_count: &mut FxHashMap<Name, u32>,
418     syntactic_name_ref_highlighting: bool,
419     element: SyntaxElement,
420 ) -> Option<(Highlight, Option<u64>)> {
421     let db = sema.db;
422     let mut binding_hash = None;
423     let highlight: Highlight = match element.kind() {
424         FN_DEF => {
425             bindings_shadow_count.clear();
426             return None;
427         }
428
429         // Highlight definitions depending on the "type" of the definition.
430         NAME => {
431             let name = element.into_node().and_then(ast::Name::cast).unwrap();
432             let name_kind = classify_name(sema, &name);
433
434             if let Some(NameClass::Definition(Definition::Local(local))) = &name_kind {
435                 if let Some(name) = local.name(db) {
436                     let shadow_count = bindings_shadow_count.entry(name.clone()).or_default();
437                     *shadow_count += 1;
438                     binding_hash = Some(calc_binding_hash(&name, *shadow_count))
439                 }
440             };
441
442             match name_kind {
443                 Some(NameClass::Definition(def)) => {
444                     highlight_name(db, def) | HighlightModifier::Definition
445                 }
446                 Some(NameClass::ConstReference(def)) => highlight_name(db, def),
447                 Some(NameClass::FieldShorthand { .. }) => HighlightTag::Field.into(),
448                 None => highlight_name_by_syntax(name) | HighlightModifier::Definition,
449             }
450         }
451
452         // Highlight references like the definitions they resolve to
453         NAME_REF if element.ancestors().any(|it| it.kind() == ATTR) => {
454             Highlight::from(HighlightTag::Function) | HighlightModifier::Attribute
455         }
456         NAME_REF => {
457             let name_ref = element.into_node().and_then(ast::NameRef::cast).unwrap();
458             match classify_name_ref(sema, &name_ref) {
459                 Some(name_kind) => match name_kind {
460                     NameRefClass::Definition(def) => {
461                         if let Definition::Local(local) = &def {
462                             if let Some(name) = local.name(db) {
463                                 let shadow_count =
464                                     bindings_shadow_count.entry(name.clone()).or_default();
465                                 binding_hash = Some(calc_binding_hash(&name, *shadow_count))
466                             }
467                         };
468                         highlight_name(db, def)
469                     }
470                     NameRefClass::FieldShorthand { .. } => HighlightTag::Field.into(),
471                 },
472                 None if syntactic_name_ref_highlighting => highlight_name_ref_by_syntax(name_ref),
473                 None => HighlightTag::UnresolvedReference.into(),
474             }
475         }
476
477         // Simple token-based highlighting
478         COMMENT => HighlightTag::Comment.into(),
479         STRING | RAW_STRING | RAW_BYTE_STRING | BYTE_STRING => HighlightTag::StringLiteral.into(),
480         ATTR => HighlightTag::Attribute.into(),
481         INT_NUMBER | FLOAT_NUMBER => HighlightTag::NumericLiteral.into(),
482         BYTE => HighlightTag::ByteLiteral.into(),
483         CHAR => HighlightTag::CharLiteral.into(),
484         QUESTION => Highlight::new(HighlightTag::Operator) | HighlightModifier::ControlFlow,
485         LIFETIME => {
486             let h = Highlight::new(HighlightTag::Lifetime);
487             match element.parent().map(|it| it.kind()) {
488                 Some(LIFETIME_PARAM) | Some(LABEL) => h | HighlightModifier::Definition,
489                 _ => h,
490             }
491         }
492         T![*] => {
493             let prefix_expr = element.parent().and_then(ast::PrefixExpr::cast)?;
494
495             let expr = prefix_expr.expr()?;
496             let ty = sema.type_of_expr(&expr)?;
497             if !ty.is_raw_ptr() {
498                 return None;
499             }
500
501             let mut h = Highlight::new(HighlightTag::Operator);
502             h |= HighlightModifier::Unsafe;
503             h
504         }
505         T![!] if element.parent().and_then(ast::MacroCall::cast).is_some() => {
506             Highlight::new(HighlightTag::Macro)
507         }
508
509         k if k.is_keyword() => {
510             let h = Highlight::new(HighlightTag::Keyword);
511             match k {
512                 T![break]
513                 | T![continue]
514                 | T![else]
515                 | T![if]
516                 | T![loop]
517                 | T![match]
518                 | T![return]
519                 | T![while]
520                 | T![in] => h | HighlightModifier::ControlFlow,
521                 T![for] if !is_child_of_impl(element) => h | HighlightModifier::ControlFlow,
522                 T![unsafe] => h | HighlightModifier::Unsafe,
523                 T![true] | T![false] => HighlightTag::BoolLiteral.into(),
524                 T![self] => HighlightTag::SelfKeyword.into(),
525                 _ => h,
526             }
527         }
528
529         _ => return None,
530     };
531
532     return Some((highlight, binding_hash));
533
534     fn calc_binding_hash(name: &Name, shadow_count: u32) -> u64 {
535         fn hash<T: std::hash::Hash + std::fmt::Debug>(x: T) -> u64 {
536             use std::{collections::hash_map::DefaultHasher, hash::Hasher};
537
538             let mut hasher = DefaultHasher::new();
539             x.hash(&mut hasher);
540             hasher.finish()
541         }
542
543         hash((name, shadow_count))
544     }
545 }
546
547 fn is_child_of_impl(element: SyntaxElement) -> bool {
548     match element.parent() {
549         Some(e) => e.kind() == IMPL_DEF,
550         _ => false,
551     }
552 }
553
554 fn highlight_name(db: &RootDatabase, def: Definition) -> Highlight {
555     match def {
556         Definition::Macro(_) => HighlightTag::Macro,
557         Definition::Field(_) => HighlightTag::Field,
558         Definition::ModuleDef(def) => match def {
559             hir::ModuleDef::Module(_) => HighlightTag::Module,
560             hir::ModuleDef::Function(func) => {
561                 let mut h = HighlightTag::Function.into();
562                 if func.is_unsafe(db) {
563                     h |= HighlightModifier::Unsafe;
564                 }
565                 return h;
566             }
567             hir::ModuleDef::Adt(hir::Adt::Struct(_)) => HighlightTag::Struct,
568             hir::ModuleDef::Adt(hir::Adt::Enum(_)) => HighlightTag::Enum,
569             hir::ModuleDef::Adt(hir::Adt::Union(_)) => HighlightTag::Union,
570             hir::ModuleDef::EnumVariant(_) => HighlightTag::EnumVariant,
571             hir::ModuleDef::Const(_) => HighlightTag::Constant,
572             hir::ModuleDef::Trait(_) => HighlightTag::Trait,
573             hir::ModuleDef::TypeAlias(_) => HighlightTag::TypeAlias,
574             hir::ModuleDef::BuiltinType(_) => HighlightTag::BuiltinType,
575             hir::ModuleDef::Static(s) => {
576                 let mut h = Highlight::new(HighlightTag::Static);
577                 if s.is_mut(db) {
578                     h |= HighlightModifier::Mutable;
579                 }
580                 return h;
581             }
582         },
583         Definition::SelfType(_) => HighlightTag::SelfType,
584         Definition::TypeParam(_) => HighlightTag::TypeParam,
585         // FIXME: distinguish between locals and parameters
586         Definition::Local(local) => {
587             let mut h = Highlight::new(HighlightTag::Local);
588             if local.is_mut(db) || local.ty(db).is_mutable_reference() {
589                 h |= HighlightModifier::Mutable;
590             }
591             return h;
592         }
593     }
594     .into()
595 }
596
597 fn highlight_name_by_syntax(name: ast::Name) -> Highlight {
598     let default = HighlightTag::UnresolvedReference;
599
600     let parent = match name.syntax().parent() {
601         Some(it) => it,
602         _ => return default.into(),
603     };
604
605     let tag = match parent.kind() {
606         STRUCT_DEF => HighlightTag::Struct,
607         ENUM_DEF => HighlightTag::Enum,
608         UNION_DEF => HighlightTag::Union,
609         TRAIT_DEF => HighlightTag::Trait,
610         TYPE_ALIAS_DEF => HighlightTag::TypeAlias,
611         TYPE_PARAM => HighlightTag::TypeParam,
612         RECORD_FIELD_DEF => HighlightTag::Field,
613         MODULE => HighlightTag::Module,
614         FN_DEF => HighlightTag::Function,
615         CONST_DEF => HighlightTag::Constant,
616         STATIC_DEF => HighlightTag::Static,
617         ENUM_VARIANT => HighlightTag::EnumVariant,
618         BIND_PAT => HighlightTag::Local,
619         _ => default,
620     };
621
622     tag.into()
623 }
624
625 fn highlight_name_ref_by_syntax(name: ast::NameRef) -> Highlight {
626     let default = HighlightTag::UnresolvedReference;
627
628     let parent = match name.syntax().parent() {
629         Some(it) => it,
630         _ => return default.into(),
631     };
632
633     let tag = match parent.kind() {
634         METHOD_CALL_EXPR => HighlightTag::Function,
635         FIELD_EXPR => HighlightTag::Field,
636         PATH_SEGMENT => {
637             let path = match parent.parent().and_then(ast::Path::cast) {
638                 Some(it) => it,
639                 _ => return default.into(),
640             };
641             let expr = match path.syntax().parent().and_then(ast::PathExpr::cast) {
642                 Some(it) => it,
643                 _ => {
644                     // within path, decide whether it is module or adt by checking for uppercase name
645                     return if name.text().chars().next().unwrap_or_default().is_uppercase() {
646                         HighlightTag::Struct
647                     } else {
648                         HighlightTag::Module
649                     }
650                     .into();
651                 }
652             };
653             let parent = match expr.syntax().parent() {
654                 Some(it) => it,
655                 None => return default.into(),
656             };
657
658             match parent.kind() {
659                 CALL_EXPR => HighlightTag::Function,
660                 _ => {
661                     if name.text().chars().next().unwrap_or_default().is_uppercase() {
662                         HighlightTag::Struct
663                     } else {
664                         HighlightTag::Constant
665                     }
666                 }
667             }
668         }
669         _ => default,
670     };
671
672     tag.into()
673 }