aboutsummaryrefslogtreecommitdiff
path: root/crates/ide/src/syntax_highlighting.rs
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ide/src/syntax_highlighting.rs')
-rw-r--r--crates/ide/src/syntax_highlighting.rs879
1 files changed, 879 insertions, 0 deletions
diff --git a/crates/ide/src/syntax_highlighting.rs b/crates/ide/src/syntax_highlighting.rs
new file mode 100644
index 000000000..25d6f7abd
--- /dev/null
+++ b/crates/ide/src/syntax_highlighting.rs
@@ -0,0 +1,879 @@
1mod tags;
2mod html;
3mod injection;
4#[cfg(test)]
5mod tests;
6
7use hir::{Name, Semantics, VariantDef};
8use ide_db::{
9 defs::{classify_name, classify_name_ref, Definition, NameClass, NameRefClass},
10 RootDatabase,
11};
12use rustc_hash::FxHashMap;
13use syntax::{
14 ast::{self, HasFormatSpecifier},
15 AstNode, AstToken, Direction, NodeOrToken, SyntaxElement,
16 SyntaxKind::*,
17 TextRange, WalkEvent, T,
18};
19
20use crate::FileId;
21
22use ast::FormatSpecifier;
23pub(crate) use html::highlight_as_html;
24pub use tags::{Highlight, HighlightModifier, HighlightModifiers, HighlightTag};
25
26#[derive(Debug, Clone)]
27pub struct HighlightedRange {
28 pub range: TextRange,
29 pub highlight: Highlight,
30 pub binding_hash: Option<u64>,
31}
32
33// Feature: Semantic Syntax Highlighting
34//
35// rust-analyzer highlights the code semantically.
36// For example, `bar` in `foo::Bar` might be colored differently depending on whether `Bar` is an enum or a trait.
37// rust-analyzer does not specify colors directly, instead it assigns tag (like `struct`) and a set of modifiers (like `declaration`) to each token.
38// It's up to the client to map those to specific colors.
39//
40// The general rule is that a reference to an entity gets colored the same way as the entity itself.
41// We also give special modifier for `mut` and `&mut` local variables.
42pub(crate) fn highlight(
43 db: &RootDatabase,
44 file_id: FileId,
45 range_to_highlight: Option<TextRange>,
46 syntactic_name_ref_highlighting: bool,
47) -> Vec<HighlightedRange> {
48 let _p = profile::span("highlight");
49 let sema = Semantics::new(db);
50
51 // Determine the root based on the given range.
52 let (root, range_to_highlight) = {
53 let source_file = sema.parse(file_id);
54 match range_to_highlight {
55 Some(range) => {
56 let node = match source_file.syntax().covering_element(range) {
57 NodeOrToken::Node(it) => it,
58 NodeOrToken::Token(it) => it.parent(),
59 };
60 (node, range)
61 }
62 None => (source_file.syntax().clone(), source_file.syntax().text_range()),
63 }
64 };
65
66 let mut bindings_shadow_count: FxHashMap<Name, u32> = FxHashMap::default();
67 // We use a stack for the DFS traversal below.
68 // When we leave a node, the we use it to flatten the highlighted ranges.
69 let mut stack = HighlightedRangeStack::new();
70
71 let mut current_macro_call: Option<ast::MacroCall> = None;
72 let mut format_string: Option<SyntaxElement> = None;
73
74 // Walk all nodes, keeping track of whether we are inside a macro or not.
75 // If in macro, expand it first and highlight the expanded code.
76 for event in root.preorder_with_tokens() {
77 match &event {
78 WalkEvent::Enter(_) => stack.push(),
79 WalkEvent::Leave(_) => stack.pop(),
80 };
81
82 let event_range = match &event {
83 WalkEvent::Enter(it) => it.text_range(),
84 WalkEvent::Leave(it) => it.text_range(),
85 };
86
87 // Element outside of the viewport, no need to highlight
88 if range_to_highlight.intersect(event_range).is_none() {
89 continue;
90 }
91
92 // Track "inside macro" state
93 match event.clone().map(|it| it.into_node().and_then(ast::MacroCall::cast)) {
94 WalkEvent::Enter(Some(mc)) => {
95 current_macro_call = Some(mc.clone());
96 if let Some(range) = macro_call_range(&mc) {
97 stack.add(HighlightedRange {
98 range,
99 highlight: HighlightTag::Macro.into(),
100 binding_hash: None,
101 });
102 }
103 if let Some(name) = mc.is_macro_rules() {
104 if let Some((highlight, binding_hash)) = highlight_element(
105 &sema,
106 &mut bindings_shadow_count,
107 syntactic_name_ref_highlighting,
108 name.syntax().clone().into(),
109 ) {
110 stack.add(HighlightedRange {
111 range: name.syntax().text_range(),
112 highlight,
113 binding_hash,
114 });
115 }
116 }
117 continue;
118 }
119 WalkEvent::Leave(Some(mc)) => {
120 assert!(current_macro_call == Some(mc));
121 current_macro_call = None;
122 format_string = None;
123 }
124 _ => (),
125 }
126
127 // Check for Rust code in documentation
128 match &event {
129 WalkEvent::Leave(NodeOrToken::Node(node)) => {
130 if let Some((doctest, range_mapping, new_comments)) =
131 injection::extract_doc_comments(node)
132 {
133 injection::highlight_doc_comment(
134 doctest,
135 range_mapping,
136 new_comments,
137 &mut stack,
138 );
139 }
140 }
141 _ => (),
142 }
143
144 let element = match event {
145 WalkEvent::Enter(it) => it,
146 WalkEvent::Leave(_) => continue,
147 };
148
149 let range = element.text_range();
150
151 let element_to_highlight = if current_macro_call.is_some() && element.kind() != COMMENT {
152 // Inside a macro -- expand it first
153 let token = match element.clone().into_token() {
154 Some(it) if it.parent().kind() == TOKEN_TREE => it,
155 _ => continue,
156 };
157 let token = sema.descend_into_macros(token.clone());
158 let parent = token.parent();
159
160 // Check if macro takes a format string and remember it for highlighting later.
161 // The macros that accept a format string expand to a compiler builtin macros
162 // `format_args` and `format_args_nl`.
163 if let Some(name) = parent
164 .parent()
165 .and_then(ast::MacroCall::cast)
166 .and_then(|mc| mc.path())
167 .and_then(|p| p.segment())
168 .and_then(|s| s.name_ref())
169 {
170 match name.text().as_str() {
171 "format_args" | "format_args_nl" => {
172 format_string = parent
173 .children_with_tokens()
174 .filter(|t| t.kind() != WHITESPACE)
175 .nth(1)
176 .filter(|e| {
177 ast::String::can_cast(e.kind())
178 || ast::RawString::can_cast(e.kind())
179 })
180 }
181 _ => {}
182 }
183 }
184
185 // We only care Name and Name_ref
186 match (token.kind(), parent.kind()) {
187 (IDENT, NAME) | (IDENT, NAME_REF) => parent.into(),
188 _ => token.into(),
189 }
190 } else {
191 element.clone()
192 };
193
194 if let Some(token) = element.as_token().cloned().and_then(ast::RawString::cast) {
195 let expanded = element_to_highlight.as_token().unwrap().clone();
196 if injection::highlight_injection(&mut stack, &sema, token, expanded).is_some() {
197 continue;
198 }
199 }
200
201 let is_format_string = format_string.as_ref() == Some(&element_to_highlight);
202
203 if let Some((highlight, binding_hash)) = highlight_element(
204 &sema,
205 &mut bindings_shadow_count,
206 syntactic_name_ref_highlighting,
207 element_to_highlight.clone(),
208 ) {
209 stack.add(HighlightedRange { range, highlight, binding_hash });
210 if let Some(string) =
211 element_to_highlight.as_token().cloned().and_then(ast::String::cast)
212 {
213 if is_format_string {
214 stack.push();
215 string.lex_format_specifier(|piece_range, kind| {
216 if let Some(highlight) = highlight_format_specifier(kind) {
217 stack.add(HighlightedRange {
218 range: piece_range + range.start(),
219 highlight: highlight.into(),
220 binding_hash: None,
221 });
222 }
223 });
224 stack.pop();
225 }
226 // Highlight escape sequences
227 if let Some(char_ranges) = string.char_ranges() {
228 stack.push();
229 for (piece_range, _) in char_ranges.iter().filter(|(_, char)| char.is_ok()) {
230 if string.text()[piece_range.start().into()..].starts_with('\\') {
231 stack.add(HighlightedRange {
232 range: piece_range + range.start(),
233 highlight: HighlightTag::EscapeSequence.into(),
234 binding_hash: None,
235 });
236 }
237 }
238 stack.pop_and_inject(None);
239 }
240 } else if let Some(string) =
241 element_to_highlight.as_token().cloned().and_then(ast::RawString::cast)
242 {
243 if is_format_string {
244 stack.push();
245 string.lex_format_specifier(|piece_range, kind| {
246 if let Some(highlight) = highlight_format_specifier(kind) {
247 stack.add(HighlightedRange {
248 range: piece_range + range.start(),
249 highlight: highlight.into(),
250 binding_hash: None,
251 });
252 }
253 });
254 stack.pop();
255 }
256 }
257 }
258 }
259
260 stack.flattened()
261}
262
263#[derive(Debug)]
264struct HighlightedRangeStack {
265 stack: Vec<Vec<HighlightedRange>>,
266}
267
268/// We use a stack to implement the flattening logic for the highlighted
269/// syntax ranges.
270impl HighlightedRangeStack {
271 fn new() -> Self {
272 Self { stack: vec![Vec::new()] }
273 }
274
275 fn push(&mut self) {
276 self.stack.push(Vec::new());
277 }
278
279 /// Flattens the highlighted ranges.
280 ///
281 /// For example `#[cfg(feature = "foo")]` contains the nested ranges:
282 /// 1) parent-range: Attribute [0, 23)
283 /// 2) child-range: String [16, 21)
284 ///
285 /// The following code implements the flattening, for our example this results to:
286 /// `[Attribute [0, 16), String [16, 21), Attribute [21, 23)]`
287 fn pop(&mut self) {
288 let children = self.stack.pop().unwrap();
289 let prev = self.stack.last_mut().unwrap();
290 let needs_flattening = !children.is_empty()
291 && !prev.is_empty()
292 && prev.last().unwrap().range.contains_range(children.first().unwrap().range);
293 if !needs_flattening {
294 prev.extend(children);
295 } else {
296 let mut parent = prev.pop().unwrap();
297 for ele in children {
298 assert!(parent.range.contains_range(ele.range));
299
300 let cloned = Self::intersect(&mut parent, &ele);
301 if !parent.range.is_empty() {
302 prev.push(parent);
303 }
304 prev.push(ele);
305 parent = cloned;
306 }
307 if !parent.range.is_empty() {
308 prev.push(parent);
309 }
310 }
311 }
312
313 /// Intersects the `HighlightedRange` `parent` with `child`.
314 /// `parent` is mutated in place, becoming the range before `child`.
315 /// Returns the range (of the same type as `parent`) *after* `child`.
316 fn intersect(parent: &mut HighlightedRange, child: &HighlightedRange) -> HighlightedRange {
317 assert!(parent.range.contains_range(child.range));
318
319 let mut cloned = parent.clone();
320 parent.range = TextRange::new(parent.range.start(), child.range.start());
321 cloned.range = TextRange::new(child.range.end(), cloned.range.end());
322
323 cloned
324 }
325
326 /// Remove the `HighlightRange` of `parent` that's currently covered by `child`.
327 fn intersect_partial(parent: &mut HighlightedRange, child: &HighlightedRange) {
328 assert!(
329 parent.range.start() <= child.range.start()
330 && parent.range.end() >= child.range.start()
331 && child.range.end() > parent.range.end()
332 );
333
334 parent.range = TextRange::new(parent.range.start(), child.range.start());
335 }
336
337 /// Similar to `pop`, but can modify arbitrary prior ranges (where `pop`)
338 /// can only modify the last range currently on the stack.
339 /// Can be used to do injections that span multiple ranges, like the
340 /// doctest injection below.
341 /// If `overwrite_parent` is non-optional, the highlighting of the parent range
342 /// is overwritten with the argument.
343 ///
344 /// Note that `pop` can be simulated by `pop_and_inject(false)` but the
345 /// latter is computationally more expensive.
346 fn pop_and_inject(&mut self, overwrite_parent: Option<Highlight>) {
347 let mut children = self.stack.pop().unwrap();
348 let prev = self.stack.last_mut().unwrap();
349 children.sort_by_key(|range| range.range.start());
350 prev.sort_by_key(|range| range.range.start());
351
352 for child in children {
353 if let Some(idx) =
354 prev.iter().position(|parent| parent.range.contains_range(child.range))
355 {
356 if let Some(tag) = overwrite_parent {
357 prev[idx].highlight = tag;
358 }
359
360 let cloned = Self::intersect(&mut prev[idx], &child);
361 let insert_idx = if prev[idx].range.is_empty() {
362 prev.remove(idx);
363 idx
364 } else {
365 idx + 1
366 };
367 prev.insert(insert_idx, child);
368 if !cloned.range.is_empty() {
369 prev.insert(insert_idx + 1, cloned);
370 }
371 } else {
372 let maybe_idx =
373 prev.iter().position(|parent| parent.range.contains(child.range.start()));
374 match (overwrite_parent, maybe_idx) {
375 (Some(_), Some(idx)) => {
376 Self::intersect_partial(&mut prev[idx], &child);
377 let insert_idx = if prev[idx].range.is_empty() {
378 prev.remove(idx);
379 idx
380 } else {
381 idx + 1
382 };
383 prev.insert(insert_idx, child);
384 }
385 (_, None) => {
386 let idx = prev
387 .binary_search_by_key(&child.range.start(), |range| range.range.start())
388 .unwrap_or_else(|x| x);
389 prev.insert(idx, child);
390 }
391 _ => {
392 unreachable!("child range should be completely contained in parent range");
393 }
394 }
395 }
396 }
397 }
398
399 fn add(&mut self, range: HighlightedRange) {
400 self.stack
401 .last_mut()
402 .expect("during DFS traversal, the stack must not be empty")
403 .push(range)
404 }
405
406 fn flattened(mut self) -> Vec<HighlightedRange> {
407 assert_eq!(
408 self.stack.len(),
409 1,
410 "after DFS traversal, the stack should only contain a single element"
411 );
412 let mut res = self.stack.pop().unwrap();
413 res.sort_by_key(|range| range.range.start());
414 // Check that ranges are sorted and disjoint
415 assert!(res
416 .iter()
417 .zip(res.iter().skip(1))
418 .all(|(left, right)| left.range.end() <= right.range.start()));
419 res
420 }
421}
422
423fn highlight_format_specifier(kind: FormatSpecifier) -> Option<HighlightTag> {
424 Some(match kind {
425 FormatSpecifier::Open
426 | FormatSpecifier::Close
427 | FormatSpecifier::Colon
428 | FormatSpecifier::Fill
429 | FormatSpecifier::Align
430 | FormatSpecifier::Sign
431 | FormatSpecifier::NumberSign
432 | FormatSpecifier::DollarSign
433 | FormatSpecifier::Dot
434 | FormatSpecifier::Asterisk
435 | FormatSpecifier::QuestionMark => HighlightTag::FormatSpecifier,
436 FormatSpecifier::Integer | FormatSpecifier::Zero => HighlightTag::NumericLiteral,
437 FormatSpecifier::Identifier => HighlightTag::Local,
438 })
439}
440
441fn macro_call_range(macro_call: &ast::MacroCall) -> Option<TextRange> {
442 let path = macro_call.path()?;
443 let name_ref = path.segment()?.name_ref()?;
444
445 let range_start = name_ref.syntax().text_range().start();
446 let mut range_end = name_ref.syntax().text_range().end();
447 for sibling in path.syntax().siblings_with_tokens(Direction::Next) {
448 match sibling.kind() {
449 T![!] | IDENT => range_end = sibling.text_range().end(),
450 _ => (),
451 }
452 }
453
454 Some(TextRange::new(range_start, range_end))
455}
456
457fn highlight_element(
458 sema: &Semantics<RootDatabase>,
459 bindings_shadow_count: &mut FxHashMap<Name, u32>,
460 syntactic_name_ref_highlighting: bool,
461 element: SyntaxElement,
462) -> Option<(Highlight, Option<u64>)> {
463 let db = sema.db;
464 let mut binding_hash = None;
465 let highlight: Highlight = match element.kind() {
466 FN => {
467 bindings_shadow_count.clear();
468 return None;
469 }
470
471 // Highlight definitions depending on the "type" of the definition.
472 NAME => {
473 let name = element.into_node().and_then(ast::Name::cast).unwrap();
474 let name_kind = classify_name(sema, &name);
475
476 if let Some(NameClass::Definition(Definition::Local(local))) = &name_kind {
477 if let Some(name) = local.name(db) {
478 let shadow_count = bindings_shadow_count.entry(name.clone()).or_default();
479 *shadow_count += 1;
480 binding_hash = Some(calc_binding_hash(&name, *shadow_count))
481 }
482 };
483
484 match name_kind {
485 Some(NameClass::ExternCrate(_)) => HighlightTag::Module.into(),
486 Some(NameClass::Definition(def)) => {
487 highlight_def(db, def) | HighlightModifier::Definition
488 }
489 Some(NameClass::ConstReference(def)) => highlight_def(db, def),
490 Some(NameClass::FieldShorthand { field, .. }) => {
491 let mut h = HighlightTag::Field.into();
492 if let Definition::Field(field) = field {
493 if let VariantDef::Union(_) = field.parent_def(db) {
494 h |= HighlightModifier::Unsafe;
495 }
496 }
497
498 h
499 }
500 None => highlight_name_by_syntax(name) | HighlightModifier::Definition,
501 }
502 }
503
504 // Highlight references like the definitions they resolve to
505 NAME_REF if element.ancestors().any(|it| it.kind() == ATTR) => {
506 Highlight::from(HighlightTag::Function) | HighlightModifier::Attribute
507 }
508 NAME_REF => {
509 let name_ref = element.into_node().and_then(ast::NameRef::cast).unwrap();
510 highlight_func_by_name_ref(sema, &name_ref).unwrap_or_else(|| {
511 match classify_name_ref(sema, &name_ref) {
512 Some(name_kind) => match name_kind {
513 NameRefClass::ExternCrate(_) => HighlightTag::Module.into(),
514 NameRefClass::Definition(def) => {
515 if let Definition::Local(local) = &def {
516 if let Some(name) = local.name(db) {
517 let shadow_count =
518 bindings_shadow_count.entry(name.clone()).or_default();
519 binding_hash = Some(calc_binding_hash(&name, *shadow_count))
520 }
521 };
522
523 let mut h = highlight_def(db, def);
524
525 if let Some(parent) = name_ref.syntax().parent() {
526 if matches!(parent.kind(), FIELD_EXPR | RECORD_PAT_FIELD) {
527 if let Definition::Field(field) = def {
528 if let VariantDef::Union(_) = field.parent_def(db) {
529 h |= HighlightModifier::Unsafe;
530 }
531 }
532 }
533 }
534
535 h
536 }
537 NameRefClass::FieldShorthand { .. } => HighlightTag::Field.into(),
538 },
539 None if syntactic_name_ref_highlighting => {
540 highlight_name_ref_by_syntax(name_ref, sema)
541 }
542 None => HighlightTag::UnresolvedReference.into(),
543 }
544 })
545 }
546
547 // Simple token-based highlighting
548 COMMENT => {
549 let comment = element.into_token().and_then(ast::Comment::cast)?;
550 let h = HighlightTag::Comment;
551 match comment.kind().doc {
552 Some(_) => h | HighlightModifier::Documentation,
553 None => h.into(),
554 }
555 }
556 STRING | RAW_STRING | RAW_BYTE_STRING | BYTE_STRING => HighlightTag::StringLiteral.into(),
557 ATTR => HighlightTag::Attribute.into(),
558 INT_NUMBER | FLOAT_NUMBER => HighlightTag::NumericLiteral.into(),
559 BYTE => HighlightTag::ByteLiteral.into(),
560 CHAR => HighlightTag::CharLiteral.into(),
561 QUESTION => Highlight::new(HighlightTag::Operator) | HighlightModifier::ControlFlow,
562 LIFETIME => {
563 let h = Highlight::new(HighlightTag::Lifetime);
564 match element.parent().map(|it| it.kind()) {
565 Some(LIFETIME_PARAM) | Some(LABEL) => h | HighlightModifier::Definition,
566 _ => h,
567 }
568 }
569 p if p.is_punct() => match p {
570 T![&] => {
571 let h = HighlightTag::Operator.into();
572 let is_unsafe = element
573 .parent()
574 .and_then(ast::RefExpr::cast)
575 .map(|ref_expr| sema.is_unsafe_ref_expr(&ref_expr))
576 .unwrap_or(false);
577 if is_unsafe {
578 h | HighlightModifier::Unsafe
579 } else {
580 h
581 }
582 }
583 T![::] | T![->] | T![=>] | T![..] | T![=] | T![@] => HighlightTag::Operator.into(),
584 T![!] if element.parent().and_then(ast::MacroCall::cast).is_some() => {
585 HighlightTag::Macro.into()
586 }
587 T![*] if element.parent().and_then(ast::PtrType::cast).is_some() => {
588 HighlightTag::Keyword.into()
589 }
590 T![*] if element.parent().and_then(ast::PrefixExpr::cast).is_some() => {
591 let prefix_expr = element.parent().and_then(ast::PrefixExpr::cast)?;
592
593 let expr = prefix_expr.expr()?;
594 let ty = sema.type_of_expr(&expr)?;
595 if ty.is_raw_ptr() {
596 HighlightTag::Operator | HighlightModifier::Unsafe
597 } else if let Some(ast::PrefixOp::Deref) = prefix_expr.op_kind() {
598 HighlightTag::Operator.into()
599 } else {
600 HighlightTag::Punctuation.into()
601 }
602 }
603 T![-] if element.parent().and_then(ast::PrefixExpr::cast).is_some() => {
604 HighlightTag::NumericLiteral.into()
605 }
606 _ if element.parent().and_then(ast::PrefixExpr::cast).is_some() => {
607 HighlightTag::Operator.into()
608 }
609 _ if element.parent().and_then(ast::BinExpr::cast).is_some() => {
610 HighlightTag::Operator.into()
611 }
612 _ if element.parent().and_then(ast::RangeExpr::cast).is_some() => {
613 HighlightTag::Operator.into()
614 }
615 _ if element.parent().and_then(ast::RangePat::cast).is_some() => {
616 HighlightTag::Operator.into()
617 }
618 _ if element.parent().and_then(ast::RestPat::cast).is_some() => {
619 HighlightTag::Operator.into()
620 }
621 _ if element.parent().and_then(ast::Attr::cast).is_some() => {
622 HighlightTag::Attribute.into()
623 }
624 _ => HighlightTag::Punctuation.into(),
625 },
626
627 k if k.is_keyword() => {
628 let h = Highlight::new(HighlightTag::Keyword);
629 match k {
630 T![break]
631 | T![continue]
632 | T![else]
633 | T![if]
634 | T![loop]
635 | T![match]
636 | T![return]
637 | T![while]
638 | T![in] => h | HighlightModifier::ControlFlow,
639 T![for] if !is_child_of_impl(&element) => h | HighlightModifier::ControlFlow,
640 T![unsafe] => h | HighlightModifier::Unsafe,
641 T![true] | T![false] => HighlightTag::BoolLiteral.into(),
642 T![self] => {
643 let self_param_is_mut = element
644 .parent()
645 .and_then(ast::SelfParam::cast)
646 .and_then(|p| p.mut_token())
647 .is_some();
648 // closure to enforce lazyness
649 let self_path = || {
650 sema.resolve_path(&element.parent()?.parent().and_then(ast::Path::cast)?)
651 };
652 if self_param_is_mut
653 || matches!(self_path(),
654 Some(hir::PathResolution::Local(local))
655 if local.is_self(db)
656 && (local.is_mut(db) || local.ty(db).is_mutable_reference())
657 )
658 {
659 HighlightTag::SelfKeyword | HighlightModifier::Mutable
660 } else {
661 HighlightTag::SelfKeyword.into()
662 }
663 }
664 T![ref] => element
665 .parent()
666 .and_then(ast::IdentPat::cast)
667 .and_then(|ident_pat| {
668 if sema.is_unsafe_ident_pat(&ident_pat) {
669 Some(HighlightModifier::Unsafe)
670 } else {
671 None
672 }
673 })
674 .map(|modifier| h | modifier)
675 .unwrap_or(h),
676 _ => h,
677 }
678 }
679
680 _ => return None,
681 };
682
683 return Some((highlight, binding_hash));
684
685 fn calc_binding_hash(name: &Name, shadow_count: u32) -> u64 {
686 fn hash<T: std::hash::Hash + std::fmt::Debug>(x: T) -> u64 {
687 use std::{collections::hash_map::DefaultHasher, hash::Hasher};
688
689 let mut hasher = DefaultHasher::new();
690 x.hash(&mut hasher);
691 hasher.finish()
692 }
693
694 hash((name, shadow_count))
695 }
696}
697
698fn is_child_of_impl(element: &SyntaxElement) -> bool {
699 match element.parent() {
700 Some(e) => e.kind() == IMPL,
701 _ => false,
702 }
703}
704
705fn highlight_func_by_name_ref(
706 sema: &Semantics<RootDatabase>,
707 name_ref: &ast::NameRef,
708) -> Option<Highlight> {
709 let method_call = name_ref.syntax().parent().and_then(ast::MethodCallExpr::cast)?;
710 highlight_method_call(sema, &method_call)
711}
712
713fn highlight_method_call(
714 sema: &Semantics<RootDatabase>,
715 method_call: &ast::MethodCallExpr,
716) -> Option<Highlight> {
717 let func = sema.resolve_method_call(&method_call)?;
718 let mut h = HighlightTag::Function.into();
719 if func.is_unsafe(sema.db) || sema.is_unsafe_method_call(&method_call) {
720 h |= HighlightModifier::Unsafe;
721 }
722 if let Some(self_param) = func.self_param(sema.db) {
723 match self_param.access(sema.db) {
724 hir::Access::Shared => (),
725 hir::Access::Exclusive => h |= HighlightModifier::Mutable,
726 hir::Access::Owned => {
727 if let Some(receiver_ty) =
728 method_call.receiver().and_then(|it| sema.type_of_expr(&it))
729 {
730 if !receiver_ty.is_copy(sema.db) {
731 h |= HighlightModifier::Consuming
732 }
733 }
734 }
735 }
736 }
737 Some(h)
738}
739
740fn highlight_def(db: &RootDatabase, def: Definition) -> Highlight {
741 match def {
742 Definition::Macro(_) => HighlightTag::Macro,
743 Definition::Field(_) => HighlightTag::Field,
744 Definition::ModuleDef(def) => match def {
745 hir::ModuleDef::Module(_) => HighlightTag::Module,
746 hir::ModuleDef::Function(func) => {
747 let mut h = HighlightTag::Function.into();
748 if func.is_unsafe(db) {
749 h |= HighlightModifier::Unsafe;
750 }
751 return h;
752 }
753 hir::ModuleDef::Adt(hir::Adt::Struct(_)) => HighlightTag::Struct,
754 hir::ModuleDef::Adt(hir::Adt::Enum(_)) => HighlightTag::Enum,
755 hir::ModuleDef::Adt(hir::Adt::Union(_)) => HighlightTag::Union,
756 hir::ModuleDef::EnumVariant(_) => HighlightTag::EnumVariant,
757 hir::ModuleDef::Const(_) => HighlightTag::Constant,
758 hir::ModuleDef::Trait(_) => HighlightTag::Trait,
759 hir::ModuleDef::TypeAlias(_) => HighlightTag::TypeAlias,
760 hir::ModuleDef::BuiltinType(_) => HighlightTag::BuiltinType,
761 hir::ModuleDef::Static(s) => {
762 let mut h = Highlight::new(HighlightTag::Static);
763 if s.is_mut(db) {
764 h |= HighlightModifier::Mutable;
765 h |= HighlightModifier::Unsafe;
766 }
767 return h;
768 }
769 },
770 Definition::SelfType(_) => HighlightTag::SelfType,
771 Definition::TypeParam(_) => HighlightTag::TypeParam,
772 Definition::Local(local) => {
773 let tag =
774 if local.is_param(db) { HighlightTag::ValueParam } else { HighlightTag::Local };
775 let mut h = Highlight::new(tag);
776 if local.is_mut(db) || local.ty(db).is_mutable_reference() {
777 h |= HighlightModifier::Mutable;
778 }
779 return h;
780 }
781 }
782 .into()
783}
784
785fn highlight_name_by_syntax(name: ast::Name) -> Highlight {
786 let default = HighlightTag::UnresolvedReference;
787
788 let parent = match name.syntax().parent() {
789 Some(it) => it,
790 _ => return default.into(),
791 };
792
793 let tag = match parent.kind() {
794 STRUCT => HighlightTag::Struct,
795 ENUM => HighlightTag::Enum,
796 UNION => HighlightTag::Union,
797 TRAIT => HighlightTag::Trait,
798 TYPE_ALIAS => HighlightTag::TypeAlias,
799 TYPE_PARAM => HighlightTag::TypeParam,
800 RECORD_FIELD => HighlightTag::Field,
801 MODULE => HighlightTag::Module,
802 FN => HighlightTag::Function,
803 CONST => HighlightTag::Constant,
804 STATIC => HighlightTag::Static,
805 VARIANT => HighlightTag::EnumVariant,
806 IDENT_PAT => HighlightTag::Local,
807 _ => default,
808 };
809
810 tag.into()
811}
812
813fn highlight_name_ref_by_syntax(name: ast::NameRef, sema: &Semantics<RootDatabase>) -> Highlight {
814 let default = HighlightTag::UnresolvedReference;
815
816 let parent = match name.syntax().parent() {
817 Some(it) => it,
818 _ => return default.into(),
819 };
820
821 match parent.kind() {
822 METHOD_CALL_EXPR => {
823 return ast::MethodCallExpr::cast(parent)
824 .and_then(|method_call| highlight_method_call(sema, &method_call))
825 .unwrap_or_else(|| HighlightTag::Function.into());
826 }
827 FIELD_EXPR => {
828 let h = HighlightTag::Field;
829 let is_union = ast::FieldExpr::cast(parent)
830 .and_then(|field_expr| {
831 let field = sema.resolve_field(&field_expr)?;
832 Some(if let VariantDef::Union(_) = field.parent_def(sema.db) {
833 true
834 } else {
835 false
836 })
837 })
838 .unwrap_or(false);
839 if is_union {
840 h | HighlightModifier::Unsafe
841 } else {
842 h.into()
843 }
844 }
845 PATH_SEGMENT => {
846 let path = match parent.parent().and_then(ast::Path::cast) {
847 Some(it) => it,
848 _ => return default.into(),
849 };
850 let expr = match path.syntax().parent().and_then(ast::PathExpr::cast) {
851 Some(it) => it,
852 _ => {
853 // within path, decide whether it is module or adt by checking for uppercase name
854 return if name.text().chars().next().unwrap_or_default().is_uppercase() {
855 HighlightTag::Struct
856 } else {
857 HighlightTag::Module
858 }
859 .into();
860 }
861 };
862 let parent = match expr.syntax().parent() {
863 Some(it) => it,
864 None => return default.into(),
865 };
866
867 match parent.kind() {
868 CALL_EXPR => HighlightTag::Function.into(),
869 _ => if name.text().chars().next().unwrap_or_default().is_uppercase() {
870 HighlightTag::Struct.into()
871 } else {
872 HighlightTag::Constant
873 }
874 .into(),
875 }
876 }
877 _ => default.into(),
878 }
879}