diff --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp --- a/clang/lib/Format/TokenAnnotator.cpp +++ b/clang/lib/Format/TokenAnnotator.cpp @@ -1734,8 +1734,11 @@ else Current.setType(TT_LineComment); } else if (Current.is(tok::r_paren)) { - if (rParenEndsCast(Current)) + if (rParenEndsCast(Current)) { Current.setType(TT_CastRParen); + assert(Current.MatchingParen); + Current.MatchingParen->setType(TT_Unknown); + } if (Current.MatchingParen && Current.Next && !Current.Next->isBinaryOperator() && !Current.Next->isOneOf(tok::semi, tok::colon, tok::l_brace, @@ -1938,8 +1941,20 @@ // Certain other tokens right before the parentheses are also signals that // this cannot be a cast. + if (LeftOfParens->is(TT_TemplateCloser)) { + if (LeftOfParens->MatchingParen) { + auto *Prev = LeftOfParens->MatchingParen->getPreviousNonComment(); + if (Prev && + Prev->isOneOf(tok::kw_const_cast, tok::kw_dynamic_cast, + tok::kw_reinterpret_cast, tok::kw_static_cast)) + // FIXME: Maybe we should handle identifiers ending with "_cast", + // e.g. bit_cast? + return true; + } + return false; + } if (LeftOfParens->isOneOf(tok::at, tok::r_square, TT_OverloadedOperator, - TT_TemplateCloser, tok::ellipsis)) + tok::ellipsis)) return false; } diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp --- a/clang/unittests/Format/FormatTest.cpp +++ b/clang/unittests/Format/FormatTest.cpp @@ -10565,6 +10565,13 @@ TEST_F(FormatTest, FormatsCasts) { verifyFormat("Type *A = static_cast(P);"); + verifyFormat("static_cast(P);"); + verifyFormat("static_cast(Fun)(Args);"); + verifyFormat("static_cast(*Fun)(Args);"); + verifyFormat("a = static_cast(*Fun)(Args);"); + verifyFormat("const_cast(*Fun)(Args);"); + verifyFormat("dynamic_cast(*Fun)(Args);"); + verifyFormat("reinterpret_cast(*Fun)(Args);"); verifyFormat("Type *A = (Type *)P;"); verifyFormat("Type *A = (vector)P;"); verifyFormat("int a = (int)(2.0f);");