1 //! Syntax highlighting for format macro strings.
3 ast::{self, FormatSpecifier, HasFormatSpecifier},
4 AstNode, AstToken, SyntaxElement, SyntaxKind, SyntaxNode, TextRange,
7 use crate::{HighlightTag, HighlightedRange, SymbolKind};
9 use super::highlights::Highlights;
12 pub(super) struct FormatStringHighlighter {
13 format_string: Option<SyntaxElement>,
16 impl FormatStringHighlighter {
17 pub(super) fn check_for_format_string(&mut self, parent: &SyntaxNode) {
18 // Check if macro takes a format string and remember it for highlighting later.
19 // The macros that accept a format string expand to a compiler builtin macros
20 // `format_args` and `format_args_nl`.
21 if let Some(name) = parent
23 .and_then(ast::MacroCall::cast)
24 .and_then(|mc| mc.path())
25 .and_then(|p| p.segment())
26 .and_then(|s| s.name_ref())
28 match name.text().as_str() {
29 "format_args" | "format_args_nl" => {
30 self.format_string = parent
31 .children_with_tokens()
32 .filter(|t| t.kind() != SyntaxKind::WHITESPACE)
34 .filter(|e| ast::String::can_cast(e.kind()))
40 pub(super) fn highlight_format_string(
42 stack: &mut Highlights,
43 string: &impl HasFormatSpecifier,
46 if self.format_string.as_ref() == Some(&SyntaxElement::from(string.syntax().clone())) {
47 string.lex_format_specifier(|piece_range, kind| {
48 if let Some(highlight) = highlight_format_specifier(kind) {
49 stack.add(HighlightedRange {
50 range: piece_range + range.start(),
51 highlight: highlight.into(),
60 fn highlight_format_specifier(kind: FormatSpecifier) -> Option<HighlightTag> {
63 | FormatSpecifier::Close
64 | FormatSpecifier::Colon
65 | FormatSpecifier::Fill
66 | FormatSpecifier::Align
67 | FormatSpecifier::Sign
68 | FormatSpecifier::NumberSign
69 | FormatSpecifier::DollarSign
70 | FormatSpecifier::Dot
71 | FormatSpecifier::Asterisk
72 | FormatSpecifier::QuestionMark => HighlightTag::FormatSpecifier,
73 FormatSpecifier::Integer | FormatSpecifier::Zero => HighlightTag::NumericLiteral,
74 FormatSpecifier::Identifier => HighlightTag::Symbol(SymbolKind::Local),