[clang] [clang-format] Fix a bug in annotating CastRParen (PR #107675)
Owen Pan via cfe-commits
cfe-commits at lists.llvm.org
Sat Sep 7 01:47:42 PDT 2024
https://github.com/owenca created https://github.com/llvm/llvm-project/pull/107675
Fixes #107568.
>From 6deac871ceae8ba3918570a4bdbd8476e014a3a1 Mon Sep 17 00:00:00 2001
From: Owen Pan <owenpiano at gmail.com>
Date: Sat, 7 Sep 2024 01:39:34 -0700
Subject: [PATCH] [clang-format] Fix a bug in annotating CastRParen
Fixes #107568.
---
clang/lib/Format/TokenAnnotator.cpp | 29 +++++++++++--------
clang/unittests/Format/TokenAnnotatorTest.cpp | 6 ++++
2 files changed, 23 insertions(+), 12 deletions(-)
diff --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp
index 6a1cf61659fd97..dfa703aed0d34d 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2874,21 +2874,26 @@ class AnnotatingParser {
if (Line.InPPDirective && AfterRParen->is(tok::minus))
return false;
+ const auto *Prev = BeforeRParen;
+
+ // Look for a function pointer type, e.g. `(*)()`.
+ if (Prev->is(tok::r_paren)) {
+ if (Prev->is(TT_CastRParen))
+ return false;
+ Prev = Prev->MatchingParen;
+ if (!Prev)
+ return false;
+ Prev = Prev->Previous;
+ if (!Prev || Prev->isNot(tok::r_paren))
+ return false;
+ Prev = Prev->MatchingParen;
+ return Prev && Prev->is(TT_FunctionTypeLParen);
+ }
+
// Search for unexpected tokens.
- for (auto *Prev = BeforeRParen; Prev != LParen; Prev = Prev->Previous) {
- if (Prev->is(tok::r_paren)) {
- if (Prev->is(TT_CastRParen))
- return false;
- Prev = Prev->MatchingParen;
- if (!Prev)
- return false;
- if (Prev->is(TT_FunctionTypeLParen))
- break;
- continue;
- }
+ for (Prev = BeforeRParen; Prev != LParen; Prev = Prev->Previous)
if (!Prev->isOneOf(tok::kw_const, tok::identifier, tok::coloncolon))
return false;
- }
return true;
}
diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 1bb796fd6f5ee9..36a6db9283893e 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -775,6 +775,12 @@ TEST_F(TokenAnnotatorTest, UnderstandsCasts) {
EXPECT_TOKEN(Tokens[8], tok::r_paren, TT_Unknown);
EXPECT_TOKEN(Tokens[9], tok::minus, TT_BinaryOperator);
+ Tokens = annotate("return (double)(foo(30)) - 15;");
+ ASSERT_EQ(Tokens.size(), 14u) << Tokens;
+ EXPECT_TOKEN(Tokens[3], tok::r_paren, TT_CastRParen);
+ EXPECT_TOKEN(Tokens[9], tok::r_paren, TT_Unknown);
+ EXPECT_TOKEN(Tokens[10], tok::minus, TT_BinaryOperator);
+
auto Style = getLLVMStyle();
Style.TypeNames.push_back("Foo");
Tokens = annotate("#define FOO(bar) foo((Foo)&bar)", Style);
More information about the cfe-commits
mailing list