]> git.lizzy.rs Git - rust.git/blob - crates/ra_ide/src/syntax_highlighting.rs
Merge #4183
[rust.git] / crates / ra_ide / src / syntax_highlighting.rs
1 //! Implements syntax highlighting.
2
3 mod tags;
4 mod html;
5 #[cfg(test)]
6 mod tests;
7
8 use hir::{Name, Semantics};
9 use ra_ide_db::{
10     defs::{classify_name, classify_name_ref, Definition, NameClass, NameRefClass},
11     RootDatabase,
12 };
13 use ra_prof::profile;
14 use ra_syntax::{
15     ast::{self, HasFormatSpecifier, HasQuotes, HasStringValue},
16     AstNode, AstToken, Direction, NodeOrToken, SyntaxElement,
17     SyntaxKind::*,
18     SyntaxToken, TextRange, WalkEvent, T,
19 };
20 use rustc_hash::FxHashMap;
21
22 use crate::{call_info::ActiveParameter, Analysis, FileId};
23
24 use ast::FormatSpecifier;
25 pub(crate) use html::highlight_as_html;
26 pub use tags::{Highlight, HighlightModifier, HighlightModifiers, HighlightTag};
27
28 #[derive(Debug, Clone)]
29 pub struct HighlightedRange {
30     pub range: TextRange,
31     pub highlight: Highlight,
32     pub binding_hash: Option<u64>,
33 }
34
35 #[derive(Debug)]
36 struct HighlightedRangeStack {
37     stack: Vec<Vec<HighlightedRange>>,
38 }
39
40 /// We use a stack to implement the flattening logic for the highlighted
41 /// syntax ranges.
42 impl HighlightedRangeStack {
43     fn new() -> Self {
44         Self { stack: vec![Vec::new()] }
45     }
46
47     fn push(&mut self) {
48         self.stack.push(Vec::new());
49     }
50
51     /// Flattens the highlighted ranges.
52     ///
53     /// For example `#[cfg(feature = "foo")]` contains the nested ranges:
54     /// 1) parent-range: Attribute [0, 23)
55     /// 2) child-range: String [16, 21)
56     ///
57     /// The following code implements the flattening, for our example this results to:
58     /// `[Attribute [0, 16), String [16, 21), Attribute [21, 23)]`
59     fn pop(&mut self) {
60         let children = self.stack.pop().unwrap();
61         let prev = self.stack.last_mut().unwrap();
62         let needs_flattening = !children.is_empty()
63             && !prev.is_empty()
64             && prev.last().unwrap().range.contains_range(children.first().unwrap().range);
65         if !needs_flattening {
66             prev.extend(children);
67         } else {
68             let mut parent = prev.pop().unwrap();
69             for ele in children {
70                 assert!(parent.range.contains_range(ele.range));
71                 let mut cloned = parent.clone();
72                 parent.range = TextRange::new(parent.range.start(), ele.range.start());
73                 cloned.range = TextRange::new(ele.range.end(), cloned.range.end());
74                 if !parent.range.is_empty() {
75                     prev.push(parent);
76                 }
77                 prev.push(ele);
78                 parent = cloned;
79             }
80             if !parent.range.is_empty() {
81                 prev.push(parent);
82             }
83         }
84     }
85
86     fn add(&mut self, range: HighlightedRange) {
87         self.stack
88             .last_mut()
89             .expect("during DFS traversal, the stack must not be empty")
90             .push(range)
91     }
92
93     fn flattened(mut self) -> Vec<HighlightedRange> {
94         assert_eq!(
95             self.stack.len(),
96             1,
97             "after DFS traversal, the stack should only contain a single element"
98         );
99         let mut res = self.stack.pop().unwrap();
100         res.sort_by_key(|range| range.range.start());
101         // Check that ranges are sorted and disjoint
102         assert!(res
103             .iter()
104             .zip(res.iter().skip(1))
105             .all(|(left, right)| left.range.end() <= right.range.start()));
106         res
107     }
108 }
109
110 pub(crate) fn highlight(
111     db: &RootDatabase,
112     file_id: FileId,
113     range_to_highlight: Option<TextRange>,
114 ) -> Vec<HighlightedRange> {
115     let _p = profile("highlight");
116     let sema = Semantics::new(db);
117
118     // Determine the root based on the given range.
119     let (root, range_to_highlight) = {
120         let source_file = sema.parse(file_id);
121         match range_to_highlight {
122             Some(range) => {
123                 let node = match source_file.syntax().covering_element(range) {
124                     NodeOrToken::Node(it) => it,
125                     NodeOrToken::Token(it) => it.parent(),
126                 };
127                 (node, range)
128             }
129             None => (source_file.syntax().clone(), source_file.syntax().text_range()),
130         }
131     };
132
133     let mut bindings_shadow_count: FxHashMap<Name, u32> = FxHashMap::default();
134     // We use a stack for the DFS traversal below.
135     // When we leave a node, the we use it to flatten the highlighted ranges.
136     let mut stack = HighlightedRangeStack::new();
137
138     let mut current_macro_call: Option<ast::MacroCall> = None;
139     let mut format_string: Option<SyntaxElement> = None;
140
141     // Walk all nodes, keeping track of whether we are inside a macro or not.
142     // If in macro, expand it first and highlight the expanded code.
143     for event in root.preorder_with_tokens() {
144         match &event {
145             WalkEvent::Enter(_) => stack.push(),
146             WalkEvent::Leave(_) => stack.pop(),
147         };
148
149         let event_range = match &event {
150             WalkEvent::Enter(it) => it.text_range(),
151             WalkEvent::Leave(it) => it.text_range(),
152         };
153
154         // Element outside of the viewport, no need to highlight
155         if range_to_highlight.intersect(event_range).is_none() {
156             continue;
157         }
158
159         // Track "inside macro" state
160         match event.clone().map(|it| it.into_node().and_then(ast::MacroCall::cast)) {
161             WalkEvent::Enter(Some(mc)) => {
162                 current_macro_call = Some(mc.clone());
163                 if let Some(range) = macro_call_range(&mc) {
164                     stack.add(HighlightedRange {
165                         range,
166                         highlight: HighlightTag::Macro.into(),
167                         binding_hash: None,
168                     });
169                 }
170                 continue;
171             }
172             WalkEvent::Leave(Some(mc)) => {
173                 assert!(current_macro_call == Some(mc));
174                 current_macro_call = None;
175                 format_string = None;
176                 continue;
177             }
178             _ => (),
179         }
180
181         let element = match event {
182             WalkEvent::Enter(it) => it,
183             WalkEvent::Leave(_) => continue,
184         };
185
186         let range = element.text_range();
187
188         let element_to_highlight = if current_macro_call.is_some() {
189             // Inside a macro -- expand it first
190             let token = match element.clone().into_token() {
191                 Some(it) if it.parent().kind() == TOKEN_TREE => it,
192                 _ => continue,
193             };
194             let token = sema.descend_into_macros(token.clone());
195             let parent = token.parent();
196
197             // Check if macro takes a format string and remember it for highlighting later.
198             // The macros that accept a format string expand to a compiler builtin macros
199             // `format_args` and `format_args_nl`.
200             if let Some(fmt_macro_call) = parent.parent().and_then(ast::MacroCall::cast) {
201                 if let Some(name) =
202                     fmt_macro_call.path().and_then(|p| p.segment()).and_then(|s| s.name_ref())
203                 {
204                     match name.text().as_str() {
205                         "format_args" | "format_args_nl" => {
206                             format_string = parent
207                                 .children_with_tokens()
208                                 .filter(|t| t.kind() != WHITESPACE)
209                                 .nth(1)
210                                 .filter(|e| {
211                                     ast::String::can_cast(e.kind())
212                                         || ast::RawString::can_cast(e.kind())
213                                 })
214                         }
215                         _ => {}
216                     }
217                 }
218             }
219
220             // We only care Name and Name_ref
221             match (token.kind(), parent.kind()) {
222                 (IDENT, NAME) | (IDENT, NAME_REF) => parent.into(),
223                 _ => token.into(),
224             }
225         } else {
226             element.clone()
227         };
228
229         if let Some(token) = element.as_token().cloned().and_then(ast::RawString::cast) {
230             let expanded = element_to_highlight.as_token().unwrap().clone();
231             if highlight_injection(&mut stack, &sema, token, expanded).is_some() {
232                 continue;
233             }
234         }
235
236         let is_format_string = format_string.as_ref() == Some(&element_to_highlight);
237
238         if let Some((highlight, binding_hash)) =
239             highlight_element(&sema, &mut bindings_shadow_count, element_to_highlight.clone())
240         {
241             stack.add(HighlightedRange { range, highlight, binding_hash });
242             if let Some(string) =
243                 element_to_highlight.as_token().cloned().and_then(ast::String::cast)
244             {
245                 stack.push();
246                 if is_format_string {
247                     string.lex_format_specifier(|piece_range, kind| {
248                         if let Some(highlight) = highlight_format_specifier(kind) {
249                             stack.add(HighlightedRange {
250                                 range: piece_range + range.start(),
251                                 highlight: highlight.into(),
252                                 binding_hash: None,
253                             });
254                         }
255                     });
256                 }
257                 stack.pop();
258             } else if let Some(string) =
259                 element_to_highlight.as_token().cloned().and_then(ast::RawString::cast)
260             {
261                 stack.push();
262                 if is_format_string {
263                     string.lex_format_specifier(|piece_range, kind| {
264                         if let Some(highlight) = highlight_format_specifier(kind) {
265                             stack.add(HighlightedRange {
266                                 range: piece_range + range.start(),
267                                 highlight: highlight.into(),
268                                 binding_hash: None,
269                             });
270                         }
271                     });
272                 }
273                 stack.pop();
274             }
275         }
276     }
277
278     stack.flattened()
279 }
280
281 fn highlight_format_specifier(kind: FormatSpecifier) -> Option<HighlightTag> {
282     Some(match kind {
283         FormatSpecifier::Open
284         | FormatSpecifier::Close
285         | FormatSpecifier::Colon
286         | FormatSpecifier::Fill
287         | FormatSpecifier::Align
288         | FormatSpecifier::Sign
289         | FormatSpecifier::NumberSign
290         | FormatSpecifier::DollarSign
291         | FormatSpecifier::Dot
292         | FormatSpecifier::Asterisk
293         | FormatSpecifier::QuestionMark => HighlightTag::FormatSpecifier,
294         FormatSpecifier::Integer | FormatSpecifier::Zero => HighlightTag::NumericLiteral,
295         FormatSpecifier::Identifier => HighlightTag::Local,
296     })
297 }
298
299 fn macro_call_range(macro_call: &ast::MacroCall) -> Option<TextRange> {
300     let path = macro_call.path()?;
301     let name_ref = path.segment()?.name_ref()?;
302
303     let range_start = name_ref.syntax().text_range().start();
304     let mut range_end = name_ref.syntax().text_range().end();
305     for sibling in path.syntax().siblings_with_tokens(Direction::Next) {
306         match sibling.kind() {
307             T![!] | IDENT => range_end = sibling.text_range().end(),
308             _ => (),
309         }
310     }
311
312     Some(TextRange::new(range_start, range_end))
313 }
314
315 fn highlight_element(
316     sema: &Semantics<RootDatabase>,
317     bindings_shadow_count: &mut FxHashMap<Name, u32>,
318     element: SyntaxElement,
319 ) -> Option<(Highlight, Option<u64>)> {
320     let db = sema.db;
321     let mut binding_hash = None;
322     let highlight: Highlight = match element.kind() {
323         FN_DEF => {
324             bindings_shadow_count.clear();
325             return None;
326         }
327
328         // Highlight definitions depending on the "type" of the definition.
329         NAME => {
330             let name = element.into_node().and_then(ast::Name::cast).unwrap();
331             let name_kind = classify_name(sema, &name);
332
333             if let Some(NameClass::Definition(Definition::Local(local))) = &name_kind {
334                 if let Some(name) = local.name(db) {
335                     let shadow_count = bindings_shadow_count.entry(name.clone()).or_default();
336                     *shadow_count += 1;
337                     binding_hash = Some(calc_binding_hash(&name, *shadow_count))
338                 }
339             };
340
341             match name_kind {
342                 Some(NameClass::Definition(def)) => {
343                     highlight_name(db, def) | HighlightModifier::Definition
344                 }
345                 Some(NameClass::ConstReference(def)) => highlight_name(db, def),
346                 None => highlight_name_by_syntax(name) | HighlightModifier::Definition,
347             }
348         }
349
350         // Highlight references like the definitions they resolve to
351         NAME_REF if element.ancestors().any(|it| it.kind() == ATTR) => return None,
352         NAME_REF => {
353             let name_ref = element.into_node().and_then(ast::NameRef::cast).unwrap();
354             match classify_name_ref(sema, &name_ref) {
355                 Some(name_kind) => match name_kind {
356                     NameRefClass::Definition(def) => {
357                         if let Definition::Local(local) = &def {
358                             if let Some(name) = local.name(db) {
359                                 let shadow_count =
360                                     bindings_shadow_count.entry(name.clone()).or_default();
361                                 binding_hash = Some(calc_binding_hash(&name, *shadow_count))
362                             }
363                         };
364                         highlight_name(db, def)
365                     }
366                     NameRefClass::FieldShorthand { .. } => HighlightTag::Field.into(),
367                 },
368                 None => HighlightTag::UnresolvedReference.into(),
369             }
370         }
371
372         // Simple token-based highlighting
373         COMMENT => HighlightTag::Comment.into(),
374         STRING | RAW_STRING | RAW_BYTE_STRING | BYTE_STRING => HighlightTag::StringLiteral.into(),
375         ATTR => HighlightTag::Attribute.into(),
376         INT_NUMBER | FLOAT_NUMBER => HighlightTag::NumericLiteral.into(),
377         BYTE => HighlightTag::ByteLiteral.into(),
378         CHAR => HighlightTag::CharLiteral.into(),
379         LIFETIME => {
380             let h = Highlight::new(HighlightTag::Lifetime);
381             match element.parent().map(|it| it.kind()) {
382                 Some(LIFETIME_PARAM) | Some(LABEL) => h | HighlightModifier::Definition,
383                 _ => h,
384             }
385         }
386
387         k if k.is_keyword() => {
388             let h = Highlight::new(HighlightTag::Keyword);
389             match k {
390                 T![break]
391                 | T![continue]
392                 | T![else]
393                 | T![for]
394                 | T![if]
395                 | T![loop]
396                 | T![match]
397                 | T![return]
398                 | T![while] => h | HighlightModifier::ControlFlow,
399                 T![unsafe] => h | HighlightModifier::Unsafe,
400                 _ => h,
401             }
402         }
403
404         _ => return None,
405     };
406
407     return Some((highlight, binding_hash));
408
409     fn calc_binding_hash(name: &Name, shadow_count: u32) -> u64 {
410         fn hash<T: std::hash::Hash + std::fmt::Debug>(x: T) -> u64 {
411             use std::{collections::hash_map::DefaultHasher, hash::Hasher};
412
413             let mut hasher = DefaultHasher::new();
414             x.hash(&mut hasher);
415             hasher.finish()
416         }
417
418         hash((name, shadow_count))
419     }
420 }
421
422 fn highlight_name(db: &RootDatabase, def: Definition) -> Highlight {
423     match def {
424         Definition::Macro(_) => HighlightTag::Macro,
425         Definition::Field(_) => HighlightTag::Field,
426         Definition::ModuleDef(def) => match def {
427             hir::ModuleDef::Module(_) => HighlightTag::Module,
428             hir::ModuleDef::Function(_) => HighlightTag::Function,
429             hir::ModuleDef::Adt(hir::Adt::Struct(_)) => HighlightTag::Struct,
430             hir::ModuleDef::Adt(hir::Adt::Enum(_)) => HighlightTag::Enum,
431             hir::ModuleDef::Adt(hir::Adt::Union(_)) => HighlightTag::Union,
432             hir::ModuleDef::EnumVariant(_) => HighlightTag::EnumVariant,
433             hir::ModuleDef::Const(_) => HighlightTag::Constant,
434             hir::ModuleDef::Static(_) => HighlightTag::Static,
435             hir::ModuleDef::Trait(_) => HighlightTag::Trait,
436             hir::ModuleDef::TypeAlias(_) => HighlightTag::TypeAlias,
437             hir::ModuleDef::BuiltinType(_) => HighlightTag::BuiltinType,
438         },
439         Definition::SelfType(_) => HighlightTag::SelfType,
440         Definition::TypeParam(_) => HighlightTag::TypeParam,
441         // FIXME: distinguish between locals and parameters
442         Definition::Local(local) => {
443             let mut h = Highlight::new(HighlightTag::Local);
444             if local.is_mut(db) || local.ty(db).is_mutable_reference() {
445                 h |= HighlightModifier::Mutable;
446             }
447             return h;
448         }
449     }
450     .into()
451 }
452
453 fn highlight_name_by_syntax(name: ast::Name) -> Highlight {
454     let default = HighlightTag::Function.into();
455
456     let parent = match name.syntax().parent() {
457         Some(it) => it,
458         _ => return default,
459     };
460
461     match parent.kind() {
462         STRUCT_DEF => HighlightTag::Struct.into(),
463         ENUM_DEF => HighlightTag::Enum.into(),
464         UNION_DEF => HighlightTag::Union.into(),
465         TRAIT_DEF => HighlightTag::Trait.into(),
466         TYPE_ALIAS_DEF => HighlightTag::TypeAlias.into(),
467         TYPE_PARAM => HighlightTag::TypeParam.into(),
468         RECORD_FIELD_DEF => HighlightTag::Field.into(),
469         _ => default,
470     }
471 }
472
473 fn highlight_injection(
474     acc: &mut HighlightedRangeStack,
475     sema: &Semantics<RootDatabase>,
476     literal: ast::RawString,
477     expanded: SyntaxToken,
478 ) -> Option<()> {
479     let active_parameter = ActiveParameter::at_token(&sema, expanded)?;
480     if !active_parameter.name.starts_with("ra_fixture") {
481         return None;
482     }
483     let value = literal.value()?;
484     let (analysis, tmp_file_id) = Analysis::from_single_file(value);
485
486     if let Some(range) = literal.open_quote_text_range() {
487         acc.add(HighlightedRange {
488             range,
489             highlight: HighlightTag::StringLiteral.into(),
490             binding_hash: None,
491         })
492     }
493
494     for mut h in analysis.highlight(tmp_file_id).unwrap() {
495         if let Some(r) = literal.map_range_up(h.range) {
496             h.range = r;
497             acc.add(h)
498         }
499     }
500
501     if let Some(range) = literal.close_quote_text_range() {
502         acc.add(HighlightedRange {
503             range,
504             highlight: HighlightTag::StringLiteral.into(),
505             binding_hash: None,
506         })
507     }
508
509     Some(())
510 }