]> git.lizzy.rs Git - rust.git/blob - crates/ide_db/src/helpers/format_string.rs
Merge #11293
[rust.git] / crates / ide_db / src / helpers / format_string.rs
1 //! Tools to work with format string literals for the `format_args!` family of macros.
2 use syntax::{ast, AstNode, AstToken};
3
4 pub fn is_format_string(string: &ast::String) -> bool {
5     // Check if `string` is a format string argument of a macro invocation.
6     // `string` is a string literal, mapped down into the innermost macro expansion.
7     // Since `format_args!` etc. remove the format string when expanding, but place all arguments
8     // in the expanded output, we know that the string token is (part of) the format string if it
9     // appears in `format_args!` (otherwise it would have been mapped down further).
10     //
11     // This setup lets us correctly highlight the components of `concat!("{}", "bla")` format
12     // strings. It still fails for `concat!("{", "}")`, but that is rare.
13
14     (|| {
15         let macro_call = string.syntax().ancestors().find_map(ast::MacroCall::cast)?;
16         let name = macro_call.path()?.segment()?.name_ref()?;
17
18         if !matches!(
19             name.text().as_str(),
20             "format_args" | "format_args_nl" | "const_format_args" | "panic_2015" | "panic_2021"
21         ) {
22             return None;
23         }
24
25         // NB: we match against `panic_2015`/`panic_2021` here because they have a special-cased arm for
26         // `"{}"`, which otherwise wouldn't get highlighted.
27
28         Some(())
29     })()
30     .is_some()
31 }