1 //! Syntax highlighting for format macro strings.
3 ast::{self, FormatSpecifier, HasFormatSpecifier},
4 AstNode, AstToken, SyntaxElement, SyntaxKind, SyntaxNode, TextRange,
7 use crate::{syntax_highlighting::HighlightedRangeStack, HighlightTag, HighlightedRange};
10 pub(super) struct FormatStringHighlighter {
11 format_string: Option<SyntaxElement>,
14 impl FormatStringHighlighter {
15 pub(super) fn check_for_format_string(&mut self, parent: &SyntaxNode) {
16 // Check if macro takes a format string and remember it for highlighting later.
17 // The macros that accept a format string expand to a compiler builtin macros
18 // `format_args` and `format_args_nl`.
19 if let Some(name) = parent
21 .and_then(ast::MacroCall::cast)
22 .and_then(|mc| mc.path())
23 .and_then(|p| p.segment())
24 .and_then(|s| s.name_ref())
26 match name.text().as_str() {
27 "format_args" | "format_args_nl" => {
28 self.format_string = parent
29 .children_with_tokens()
30 .filter(|t| t.kind() != SyntaxKind::WHITESPACE)
32 .filter(|e| ast::String::can_cast(e.kind()))
38 pub(super) fn highlight_format_string(
40 range_stack: &mut HighlightedRangeStack,
41 string: &impl HasFormatSpecifier,
44 if self.format_string.as_ref() == Some(&SyntaxElement::from(string.syntax().clone())) {
46 string.lex_format_specifier(|piece_range, kind| {
47 if let Some(highlight) = highlight_format_specifier(kind) {
48 range_stack.add(HighlightedRange {
49 range: piece_range + range.start(),
50 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::Local,