]> git.lizzy.rs Git - rust.git/blob - crates/ra_ide/src/syntax_highlighting.rs
Add boolean literals to package.json
[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                 if let Some(name) = mc.is_macro_rules() {
171                     if let Some((highlight, binding_hash)) = highlight_element(
172                         &sema,
173                         &mut bindings_shadow_count,
174                         name.syntax().clone().into(),
175                     ) {
176                         stack.add(HighlightedRange {
177                             range: name.syntax().text_range(),
178                             highlight,
179                             binding_hash,
180                         });
181                     }
182                 }
183                 continue;
184             }
185             WalkEvent::Leave(Some(mc)) => {
186                 assert!(current_macro_call == Some(mc));
187                 current_macro_call = None;
188                 format_string = None;
189                 continue;
190             }
191             _ => (),
192         }
193
194         let element = match event {
195             WalkEvent::Enter(it) => it,
196             WalkEvent::Leave(_) => continue,
197         };
198
199         let range = element.text_range();
200
201         let element_to_highlight = if current_macro_call.is_some() {
202             // Inside a macro -- expand it first
203             let token = match element.clone().into_token() {
204                 Some(it) if it.parent().kind() == TOKEN_TREE => it,
205                 _ => continue,
206             };
207             let token = sema.descend_into_macros(token.clone());
208             let parent = token.parent();
209
210             // Check if macro takes a format string and remember it for highlighting later.
211             // The macros that accept a format string expand to a compiler builtin macros
212             // `format_args` and `format_args_nl`.
213             if let Some(fmt_macro_call) = parent.parent().and_then(ast::MacroCall::cast) {
214                 if let Some(name) =
215                     fmt_macro_call.path().and_then(|p| p.segment()).and_then(|s| s.name_ref())
216                 {
217                     match name.text().as_str() {
218                         "format_args" | "format_args_nl" => {
219                             format_string = parent
220                                 .children_with_tokens()
221                                 .filter(|t| t.kind() != WHITESPACE)
222                                 .nth(1)
223                                 .filter(|e| {
224                                     ast::String::can_cast(e.kind())
225                                         || ast::RawString::can_cast(e.kind())
226                                 })
227                         }
228                         _ => {}
229                     }
230                 }
231             }
232
233             // We only care Name and Name_ref
234             match (token.kind(), parent.kind()) {
235                 (IDENT, NAME) | (IDENT, NAME_REF) => parent.into(),
236                 _ => token.into(),
237             }
238         } else {
239             element.clone()
240         };
241
242         if let Some(token) = element.as_token().cloned().and_then(ast::RawString::cast) {
243             let expanded = element_to_highlight.as_token().unwrap().clone();
244             if highlight_injection(&mut stack, &sema, token, expanded).is_some() {
245                 continue;
246             }
247         }
248
249         let is_format_string = format_string.as_ref() == Some(&element_to_highlight);
250
251         if let Some((highlight, binding_hash)) =
252             highlight_element(&sema, &mut bindings_shadow_count, element_to_highlight.clone())
253         {
254             stack.add(HighlightedRange { range, highlight, binding_hash });
255             if let Some(string) =
256                 element_to_highlight.as_token().cloned().and_then(ast::String::cast)
257             {
258                 stack.push();
259                 if is_format_string {
260                     string.lex_format_specifier(|piece_range, kind| {
261                         if let Some(highlight) = highlight_format_specifier(kind) {
262                             stack.add(HighlightedRange {
263                                 range: piece_range + range.start(),
264                                 highlight: highlight.into(),
265                                 binding_hash: None,
266                             });
267                         }
268                     });
269                 }
270                 stack.pop();
271             } else if let Some(string) =
272                 element_to_highlight.as_token().cloned().and_then(ast::RawString::cast)
273             {
274                 stack.push();
275                 if is_format_string {
276                     string.lex_format_specifier(|piece_range, kind| {
277                         if let Some(highlight) = highlight_format_specifier(kind) {
278                             stack.add(HighlightedRange {
279                                 range: piece_range + range.start(),
280                                 highlight: highlight.into(),
281                                 binding_hash: None,
282                             });
283                         }
284                     });
285                 }
286                 stack.pop();
287             }
288         }
289     }
290
291     stack.flattened()
292 }
293
294 fn highlight_format_specifier(kind: FormatSpecifier) -> Option<HighlightTag> {
295     Some(match kind {
296         FormatSpecifier::Open
297         | FormatSpecifier::Close
298         | FormatSpecifier::Colon
299         | FormatSpecifier::Fill
300         | FormatSpecifier::Align
301         | FormatSpecifier::Sign
302         | FormatSpecifier::NumberSign
303         | FormatSpecifier::DollarSign
304         | FormatSpecifier::Dot
305         | FormatSpecifier::Asterisk
306         | FormatSpecifier::QuestionMark => HighlightTag::FormatSpecifier,
307         FormatSpecifier::Integer | FormatSpecifier::Zero => HighlightTag::NumericLiteral,
308         FormatSpecifier::Identifier => HighlightTag::Local,
309     })
310 }
311
312 fn macro_call_range(macro_call: &ast::MacroCall) -> Option<TextRange> {
313     let path = macro_call.path()?;
314     let name_ref = path.segment()?.name_ref()?;
315
316     let range_start = name_ref.syntax().text_range().start();
317     let mut range_end = name_ref.syntax().text_range().end();
318     for sibling in path.syntax().siblings_with_tokens(Direction::Next) {
319         match sibling.kind() {
320             T![!] | IDENT => range_end = sibling.text_range().end(),
321             _ => (),
322         }
323     }
324
325     Some(TextRange::new(range_start, range_end))
326 }
327
328 fn highlight_element(
329     sema: &Semantics<RootDatabase>,
330     bindings_shadow_count: &mut FxHashMap<Name, u32>,
331     element: SyntaxElement,
332 ) -> Option<(Highlight, Option<u64>)> {
333     let db = sema.db;
334     let mut binding_hash = None;
335     let highlight: Highlight = match element.kind() {
336         FN_DEF => {
337             bindings_shadow_count.clear();
338             return None;
339         }
340
341         // Highlight definitions depending on the "type" of the definition.
342         NAME => {
343             let name = element.into_node().and_then(ast::Name::cast).unwrap();
344             let name_kind = classify_name(sema, &name);
345
346             if let Some(NameClass::Definition(Definition::Local(local))) = &name_kind {
347                 if let Some(name) = local.name(db) {
348                     let shadow_count = bindings_shadow_count.entry(name.clone()).or_default();
349                     *shadow_count += 1;
350                     binding_hash = Some(calc_binding_hash(&name, *shadow_count))
351                 }
352             };
353
354             match name_kind {
355                 Some(NameClass::Definition(def)) => {
356                     highlight_name(db, def) | HighlightModifier::Definition
357                 }
358                 Some(NameClass::ConstReference(def)) => highlight_name(db, def),
359                 None => highlight_name_by_syntax(name) | HighlightModifier::Definition,
360             }
361         }
362
363         // Highlight references like the definitions they resolve to
364         NAME_REF if element.ancestors().any(|it| it.kind() == ATTR) => {
365             Highlight::from(HighlightTag::Function) | HighlightModifier::Attribute
366         }
367         NAME_REF => {
368             let name_ref = element.into_node().and_then(ast::NameRef::cast).unwrap();
369             match classify_name_ref(sema, &name_ref) {
370                 Some(name_kind) => match name_kind {
371                     NameRefClass::Definition(def) => {
372                         if let Definition::Local(local) = &def {
373                             if let Some(name) = local.name(db) {
374                                 let shadow_count =
375                                     bindings_shadow_count.entry(name.clone()).or_default();
376                                 binding_hash = Some(calc_binding_hash(&name, *shadow_count))
377                             }
378                         };
379                         highlight_name(db, def)
380                     }
381                     NameRefClass::FieldShorthand { .. } => HighlightTag::Field.into(),
382                 },
383                 None => HighlightTag::UnresolvedReference.into(),
384             }
385         }
386
387         // Simple token-based highlighting
388         COMMENT => HighlightTag::Comment.into(),
389         STRING | RAW_STRING | RAW_BYTE_STRING | BYTE_STRING => HighlightTag::StringLiteral.into(),
390         ATTR => HighlightTag::Attribute.into(),
391         INT_NUMBER | FLOAT_NUMBER => HighlightTag::NumericLiteral.into(),
392         BYTE => HighlightTag::ByteLiteral.into(),
393         CHAR => HighlightTag::CharLiteral.into(),
394         LIFETIME => {
395             let h = Highlight::new(HighlightTag::Lifetime);
396             match element.parent().map(|it| it.kind()) {
397                 Some(LIFETIME_PARAM) | Some(LABEL) => h | HighlightModifier::Definition,
398                 _ => h,
399             }
400         }
401
402         k if k.is_keyword() => {
403             let h = Highlight::new(HighlightTag::Keyword);
404             match k {
405                 T![break]
406                 | T![continue]
407                 | T![else]
408                 | T![if]
409                 | T![loop]
410                 | T![match]
411                 | T![return]
412                 | T![while]
413                 | T![in] => h | HighlightModifier::ControlFlow,
414                 T![for] if !is_child_of_impl(element) => h | HighlightModifier::ControlFlow,
415                 T![unsafe] => h | HighlightModifier::Unsafe,
416                 T![true] | T![false] => HighlightTag::BoolLiteral.into(),
417                 _ => h,
418             }
419         }
420
421         _ => return None,
422     };
423
424     return Some((highlight, binding_hash));
425
426     fn calc_binding_hash(name: &Name, shadow_count: u32) -> u64 {
427         fn hash<T: std::hash::Hash + std::fmt::Debug>(x: T) -> u64 {
428             use std::{collections::hash_map::DefaultHasher, hash::Hasher};
429
430             let mut hasher = DefaultHasher::new();
431             x.hash(&mut hasher);
432             hasher.finish()
433         }
434
435         hash((name, shadow_count))
436     }
437 }
438
439 fn is_child_of_impl(element: SyntaxElement) -> bool {
440     match element.parent() {
441         Some(e) => e.kind() == IMPL_DEF,
442         _ => false,
443     }
444 }
445
446 fn highlight_name(db: &RootDatabase, def: Definition) -> Highlight {
447     match def {
448         Definition::Macro(_) => HighlightTag::Macro,
449         Definition::Field(_) => HighlightTag::Field,
450         Definition::ModuleDef(def) => match def {
451             hir::ModuleDef::Module(_) => HighlightTag::Module,
452             hir::ModuleDef::Function(_) => HighlightTag::Function,
453             hir::ModuleDef::Adt(hir::Adt::Struct(_)) => HighlightTag::Struct,
454             hir::ModuleDef::Adt(hir::Adt::Enum(_)) => HighlightTag::Enum,
455             hir::ModuleDef::Adt(hir::Adt::Union(_)) => HighlightTag::Union,
456             hir::ModuleDef::EnumVariant(_) => HighlightTag::EnumVariant,
457             hir::ModuleDef::Const(_) => HighlightTag::Constant,
458             hir::ModuleDef::Trait(_) => HighlightTag::Trait,
459             hir::ModuleDef::TypeAlias(_) => HighlightTag::TypeAlias,
460             hir::ModuleDef::BuiltinType(_) => HighlightTag::BuiltinType,
461             hir::ModuleDef::Static(s) => {
462                 let mut h = Highlight::new(HighlightTag::Static);
463                 if s.is_mut(db) {
464                     h |= HighlightModifier::Mutable;
465                 }
466                 return h;
467             }
468         },
469         Definition::SelfType(_) => HighlightTag::SelfType,
470         Definition::TypeParam(_) => HighlightTag::TypeParam,
471         // FIXME: distinguish between locals and parameters
472         Definition::Local(local) => {
473             let mut h = Highlight::new(HighlightTag::Local);
474             if local.is_mut(db) || local.ty(db).is_mutable_reference() {
475                 h |= HighlightModifier::Mutable;
476             }
477             return h;
478         }
479     }
480     .into()
481 }
482
483 fn highlight_name_by_syntax(name: ast::Name) -> Highlight {
484     let default = HighlightTag::UnresolvedReference;
485
486     let parent = match name.syntax().parent() {
487         Some(it) => it,
488         _ => return default.into(),
489     };
490
491     let tag = match parent.kind() {
492         STRUCT_DEF => HighlightTag::Struct,
493         ENUM_DEF => HighlightTag::Enum,
494         UNION_DEF => HighlightTag::Union,
495         TRAIT_DEF => HighlightTag::Trait,
496         TYPE_ALIAS_DEF => HighlightTag::TypeAlias,
497         TYPE_PARAM => HighlightTag::TypeParam,
498         RECORD_FIELD_DEF => HighlightTag::Field,
499         MODULE => HighlightTag::Module,
500         FN_DEF => HighlightTag::Function,
501         CONST_DEF => HighlightTag::Constant,
502         STATIC_DEF => HighlightTag::Static,
503         ENUM_VARIANT => HighlightTag::EnumVariant,
504         BIND_PAT => HighlightTag::Local,
505         _ => default,
506     };
507
508     tag.into()
509 }
510
511 fn highlight_injection(
512     acc: &mut HighlightedRangeStack,
513     sema: &Semantics<RootDatabase>,
514     literal: ast::RawString,
515     expanded: SyntaxToken,
516 ) -> Option<()> {
517     let active_parameter = ActiveParameter::at_token(&sema, expanded)?;
518     if !active_parameter.name.starts_with("ra_fixture") {
519         return None;
520     }
521     let value = literal.value()?;
522     let (analysis, tmp_file_id) = Analysis::from_single_file(value);
523
524     if let Some(range) = literal.open_quote_text_range() {
525         acc.add(HighlightedRange {
526             range,
527             highlight: HighlightTag::StringLiteral.into(),
528             binding_hash: None,
529         })
530     }
531
532     for mut h in analysis.highlight(tmp_file_id).unwrap() {
533         if let Some(r) = literal.map_range_up(h.range) {
534             h.range = r;
535             acc.add(h)
536         }
537     }
538
539     if let Some(range) = literal.close_quote_text_range() {
540         acc.add(HighlightedRange {
541             range,
542             highlight: HighlightTag::StringLiteral.into(),
543             binding_hash: None,
544         })
545     }
546
547     Some(())
548 }