]> git.lizzy.rs Git - rust.git/blob - crates/ra_ide/src/syntax_highlighting.rs
Implement syntax highlighting for format strings
[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::call_info_for_token, 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             && children.first().unwrap().range.is_subrange(&prev.last().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!(ele.range.is_subrange(&parent.range));
71                 let mut cloned = parent.clone();
72                 parent.range = TextRange::from_to(parent.range.start(), ele.range.start());
73                 cloned.range = TextRange::from_to(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.intersection(&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 remeber 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 =
237             format_string.as_ref().map(|fs| fs == &element_to_highlight).unwrap_or_default();
238
239         if let Some((highlight, binding_hash)) =
240             highlight_element(&sema, &mut bindings_shadow_count, element_to_highlight.clone())
241         {
242             stack.add(HighlightedRange { range, highlight, binding_hash });
243             if let Some(string) =
244                 element_to_highlight.as_token().cloned().and_then(ast::String::cast)
245             {
246                 stack.push();
247                 if is_format_string {
248                     string.lex_format_specifier(&mut |piece_range, kind| {
249                         let highlight = match kind {
250                             FormatSpecifier::Open
251                             | FormatSpecifier::Close
252                             | FormatSpecifier::Colon
253                             | FormatSpecifier::Fill
254                             | FormatSpecifier::Align
255                             | FormatSpecifier::Sign
256                             | FormatSpecifier::NumberSign
257                             | FormatSpecifier::DollarSign
258                             | FormatSpecifier::Dot
259                             | FormatSpecifier::Asterisk
260                             | FormatSpecifier::QuestionMark => HighlightTag::Attribute,
261                             FormatSpecifier::Integer | FormatSpecifier::Zero => {
262                                 HighlightTag::NumericLiteral
263                             }
264                             FormatSpecifier::Identifier => HighlightTag::Local,
265                         };
266                         stack.add(HighlightedRange {
267                             range: piece_range + range.start(),
268                             highlight: highlight.into(),
269                             binding_hash: None,
270                         });
271                     });
272                 }
273                 stack.pop();
274             }
275         }
276     }
277
278     stack.flattened()
279 }
280
281 fn macro_call_range(macro_call: &ast::MacroCall) -> Option<TextRange> {
282     let path = macro_call.path()?;
283     let name_ref = path.segment()?.name_ref()?;
284
285     let range_start = name_ref.syntax().text_range().start();
286     let mut range_end = name_ref.syntax().text_range().end();
287     for sibling in path.syntax().siblings_with_tokens(Direction::Next) {
288         match sibling.kind() {
289             T![!] | IDENT => range_end = sibling.text_range().end(),
290             _ => (),
291         }
292     }
293
294     Some(TextRange::from_to(range_start, range_end))
295 }
296
297 fn highlight_element(
298     sema: &Semantics<RootDatabase>,
299     bindings_shadow_count: &mut FxHashMap<Name, u32>,
300     element: SyntaxElement,
301 ) -> Option<(Highlight, Option<u64>)> {
302     let db = sema.db;
303     let mut binding_hash = None;
304     let highlight: Highlight = match element.kind() {
305         FN_DEF => {
306             bindings_shadow_count.clear();
307             return None;
308         }
309
310         // Highlight definitions depending on the "type" of the definition.
311         NAME => {
312             let name = element.into_node().and_then(ast::Name::cast).unwrap();
313             let name_kind = classify_name(sema, &name);
314
315             if let Some(NameClass::Definition(Definition::Local(local))) = &name_kind {
316                 if let Some(name) = local.name(db) {
317                     let shadow_count = bindings_shadow_count.entry(name.clone()).or_default();
318                     *shadow_count += 1;
319                     binding_hash = Some(calc_binding_hash(&name, *shadow_count))
320                 }
321             };
322
323             match name_kind {
324                 Some(NameClass::Definition(def)) => {
325                     highlight_name(db, def) | HighlightModifier::Definition
326                 }
327                 Some(NameClass::ConstReference(def)) => highlight_name(db, def),
328                 None => highlight_name_by_syntax(name) | HighlightModifier::Definition,
329             }
330         }
331
332         // Highlight references like the definitions they resolve to
333         NAME_REF if element.ancestors().any(|it| it.kind() == ATTR) => return None,
334         NAME_REF => {
335             let name_ref = element.into_node().and_then(ast::NameRef::cast).unwrap();
336             let name_kind = classify_name_ref(sema, &name_ref)?;
337
338             match name_kind {
339                 NameRefClass::Definition(def) => {
340                     if let Definition::Local(local) = &def {
341                         if let Some(name) = local.name(db) {
342                             let shadow_count =
343                                 bindings_shadow_count.entry(name.clone()).or_default();
344                             binding_hash = Some(calc_binding_hash(&name, *shadow_count))
345                         }
346                     };
347                     highlight_name(db, def)
348                 }
349                 NameRefClass::FieldShorthand { .. } => HighlightTag::Field.into(),
350             }
351         }
352
353         // Simple token-based highlighting
354         COMMENT => HighlightTag::Comment.into(),
355         STRING | RAW_STRING | RAW_BYTE_STRING | BYTE_STRING => HighlightTag::StringLiteral.into(),
356         ATTR => HighlightTag::Attribute.into(),
357         INT_NUMBER | FLOAT_NUMBER => HighlightTag::NumericLiteral.into(),
358         BYTE => HighlightTag::ByteLiteral.into(),
359         CHAR => HighlightTag::CharLiteral.into(),
360         LIFETIME => {
361             let h = Highlight::new(HighlightTag::Lifetime);
362             match element.parent().map(|it| it.kind()) {
363                 Some(LIFETIME_PARAM) | Some(LABEL) => h | HighlightModifier::Definition,
364                 _ => h,
365             }
366         }
367
368         k if k.is_keyword() => {
369             let h = Highlight::new(HighlightTag::Keyword);
370             match k {
371                 T![break]
372                 | T![continue]
373                 | T![else]
374                 | T![for]
375                 | T![if]
376                 | T![loop]
377                 | T![match]
378                 | T![return]
379                 | T![while] => h | HighlightModifier::ControlFlow,
380                 T![unsafe] => h | HighlightModifier::Unsafe,
381                 _ => h,
382             }
383         }
384
385         _ => return None,
386     };
387
388     return Some((highlight, binding_hash));
389
390     fn calc_binding_hash(name: &Name, shadow_count: u32) -> u64 {
391         fn hash<T: std::hash::Hash + std::fmt::Debug>(x: T) -> u64 {
392             use std::{collections::hash_map::DefaultHasher, hash::Hasher};
393
394             let mut hasher = DefaultHasher::new();
395             x.hash(&mut hasher);
396             hasher.finish()
397         }
398
399         hash((name, shadow_count))
400     }
401 }
402
403 fn highlight_name(db: &RootDatabase, def: Definition) -> Highlight {
404     match def {
405         Definition::Macro(_) => HighlightTag::Macro,
406         Definition::StructField(_) => HighlightTag::Field,
407         Definition::ModuleDef(def) => match def {
408             hir::ModuleDef::Module(_) => HighlightTag::Module,
409             hir::ModuleDef::Function(_) => HighlightTag::Function,
410             hir::ModuleDef::Adt(hir::Adt::Struct(_)) => HighlightTag::Struct,
411             hir::ModuleDef::Adt(hir::Adt::Enum(_)) => HighlightTag::Enum,
412             hir::ModuleDef::Adt(hir::Adt::Union(_)) => HighlightTag::Union,
413             hir::ModuleDef::EnumVariant(_) => HighlightTag::EnumVariant,
414             hir::ModuleDef::Const(_) => HighlightTag::Constant,
415             hir::ModuleDef::Static(_) => HighlightTag::Static,
416             hir::ModuleDef::Trait(_) => HighlightTag::Trait,
417             hir::ModuleDef::TypeAlias(_) => HighlightTag::TypeAlias,
418             hir::ModuleDef::BuiltinType(_) => HighlightTag::BuiltinType,
419         },
420         Definition::SelfType(_) => HighlightTag::SelfType,
421         Definition::TypeParam(_) => HighlightTag::TypeParam,
422         // FIXME: distinguish between locals and parameters
423         Definition::Local(local) => {
424             let mut h = Highlight::new(HighlightTag::Local);
425             if local.is_mut(db) || local.ty(db).is_mutable_reference() {
426                 h |= HighlightModifier::Mutable;
427             }
428             return h;
429         }
430     }
431     .into()
432 }
433
434 fn highlight_name_by_syntax(name: ast::Name) -> Highlight {
435     let default = HighlightTag::Function.into();
436
437     let parent = match name.syntax().parent() {
438         Some(it) => it,
439         _ => return default,
440     };
441
442     match parent.kind() {
443         STRUCT_DEF => HighlightTag::Struct.into(),
444         ENUM_DEF => HighlightTag::Enum.into(),
445         UNION_DEF => HighlightTag::Union.into(),
446         TRAIT_DEF => HighlightTag::Trait.into(),
447         TYPE_ALIAS_DEF => HighlightTag::TypeAlias.into(),
448         TYPE_PARAM => HighlightTag::TypeParam.into(),
449         RECORD_FIELD_DEF => HighlightTag::Field.into(),
450         _ => default,
451     }
452 }
453
454 fn highlight_injection(
455     acc: &mut HighlightedRangeStack,
456     sema: &Semantics<RootDatabase>,
457     literal: ast::RawString,
458     expanded: SyntaxToken,
459 ) -> Option<()> {
460     let call_info = call_info_for_token(&sema, expanded)?;
461     let idx = call_info.active_parameter?;
462     let name = call_info.signature.parameter_names.get(idx)?;
463     if !name.starts_with("ra_fixture") {
464         return None;
465     }
466     let value = literal.value()?;
467     let (analysis, tmp_file_id) = Analysis::from_single_file(value);
468
469     if let Some(range) = literal.open_quote_text_range() {
470         acc.add(HighlightedRange {
471             range,
472             highlight: HighlightTag::StringLiteral.into(),
473             binding_hash: None,
474         })
475     }
476
477     for mut h in analysis.highlight(tmp_file_id).unwrap() {
478         if let Some(r) = literal.map_range_up(h.range) {
479             h.range = r;
480             acc.add(h)
481         }
482     }
483
484     if let Some(range) = literal.close_quote_text_range() {
485         acc.add(HighlightedRange {
486             range,
487             highlight: HighlightTag::StringLiteral.into(),
488             binding_hash: None,
489         })
490     }
491
492     Some(())
493 }