@@ -28,9 +28,18 @@ pub(super) fn highlight_format_string(
2828}
2929
3030fn is_format_string ( string : & ast:: String ) -> Option < ( ) > {
31- let parent = string. syntax ( ) . parent ( ) ?;
31+ // Check if `string` is a format string argument of a macro invocation.
32+ // `string` is a string literal, mapped down into the innermost macro expansion.
33+ // Since `format_args!` etc. remove the format string when expanding, but place all arguments
34+ // in the expanded output, we know that the string token is (part of) the format string if it
35+ // appears in `format_args!` (otherwise it would have been mapped down further).
36+ //
37+ // This setup lets us correctly highlight the components of `concat!("{}", "bla")` format
38+ // strings. It still fails for `concat!("{", "}")`, but that is rare.
39+
40+ let macro_call = string. syntax ( ) . ancestors ( ) . find_map ( ast:: MacroCall :: cast) ?;
41+ let name = macro_call. path ( ) ?. segment ( ) ?. name_ref ( ) ?;
3242
33- let name = parent. parent ( ) . and_then ( ast:: MacroCall :: cast) ?. path ( ) ?. segment ( ) ?. name_ref ( ) ?;
3443 if !matches ! (
3544 name. text( ) . as_str( ) ,
3645 "format_args" | "format_args_nl" | "const_format_args" | "panic_2015" | "panic_2021"
@@ -41,13 +50,6 @@ fn is_format_string(string: &ast::String) -> Option<()> {
4150 // NB: we match against `panic_2015`/`panic_2021` here because they have a special-cased arm for
4251 // `"{}"`, which otherwise wouldn't get highlighted.
4352
44- let first_literal = parent
45- . children_with_tokens ( )
46- . find_map ( |it| it. as_token ( ) . cloned ( ) . and_then ( ast:: String :: cast) ) ?;
47- if & first_literal != string {
48- return None ;
49- }
50-
5153 Some ( ( ) )
5254}
5355
0 commit comments