1 //! Syntax highlighting for format macro strings.
2 use ide_db::SymbolKind;
4 ast::{self, FormatSpecifier, HasFormatSpecifier},
5 AstNode, AstToken, TextRange,
8 use crate::{syntax_highlighting::highlights::Highlights, HlRange, HlTag};
10 pub(super) fn highlight_format_string(
11 stack: &mut Highlights,
13 expanded_string: &ast::String,
16 if is_format_string(expanded_string).is_none() {
20 string.lex_format_specifier(|piece_range, kind| {
21 if let Some(highlight) = highlight_format_specifier(kind) {
23 range: piece_range + range.start(),
24 highlight: highlight.into(),
31 fn is_format_string(string: &ast::String) -> Option<()> {
32 // Check if `string` is a format string argument of a macro invocation.
33 // `string` is a string literal, mapped down into the innermost macro expansion.
34 // Since `format_args!` etc. remove the format string when expanding, but place all arguments
35 // in the expanded output, we know that the string token is (part of) the format string if it
36 // appears in `format_args!` (otherwise it would have been mapped down further).
38 // This setup lets us correctly highlight the components of `concat!("{}", "bla")` format
39 // strings. It still fails for `concat!("{", "}")`, but that is rare.
41 let macro_call = string.syntax().ancestors().find_map(ast::MacroCall::cast)?;
42 let name = macro_call.path()?.segment()?.name_ref()?;
46 "format_args" | "format_args_nl" | "const_format_args" | "panic_2015" | "panic_2021"
51 // NB: we match against `panic_2015`/`panic_2021` here because they have a special-cased arm for
52 // `"{}"`, which otherwise wouldn't get highlighted.
57 fn highlight_format_specifier(kind: FormatSpecifier) -> Option<HlTag> {
60 | FormatSpecifier::Close
61 | FormatSpecifier::Colon
62 | FormatSpecifier::Fill
63 | FormatSpecifier::Align
64 | FormatSpecifier::Sign
65 | FormatSpecifier::NumberSign
66 | FormatSpecifier::DollarSign
67 | FormatSpecifier::Dot
68 | FormatSpecifier::Asterisk
69 | FormatSpecifier::QuestionMark => HlTag::FormatSpecifier,
71 FormatSpecifier::Integer | FormatSpecifier::Zero => HlTag::NumericLiteral,
73 FormatSpecifier::Identifier => HlTag::Symbol(SymbolKind::Local),