[clang] [clang-format] Correctly annotate ObjC `* __autoreleasing *` (PR #138799)
Owen Pan via cfe-commits
cfe-commits at lists.llvm.org
Tue May 6 20:21:35 PDT 2025
https://github.com/owenca created https://github.com/llvm/llvm-project/pull/138799
Fix #138484
>From ec9f832cedf7abd4d90d8cf3dca45ee128b922a9 Mon Sep 17 00:00:00 2001
From: Owen Pan <owenpiano at gmail.com>
Date: Tue, 6 May 2025 20:13:26 -0700
Subject: [PATCH] [clang-format] Correctly annotate ObjC `* __autoreleasing *`
Fix #138484
---
clang/lib/Format/FormatToken.h | 8 ++++++++
clang/lib/Format/TokenAnnotator.cpp | 3 ++-
clang/unittests/Format/TokenAnnotatorTest.cpp | 6 ++++++
3 files changed, 16 insertions(+), 1 deletion(-)
diff --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index 946cd7b81587f..b570171d032ac 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -711,6 +711,14 @@ struct FormatToken {
tok::objc_package, tok::objc_private);
}
+ bool isObjCLifetimeQualifier(const FormatStyle &Style) const {
+ if (Style.Language != FormatStyle::LK_ObjC || !TokenText.starts_with("__"))
+ return false;
+ const auto Qualifier = TokenText.substr(2);
+ return Qualifier == "autoreleasing" || Qualifier == "strong" ||
+ Qualifier == "weak" || Qualifier == "unsafe_unretained";
+ }
+
/// Returns whether \p Tok is ([{ or an opening < of a template or in
/// protos.
bool opensScope() const {
diff --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp
index ac6551b2bd1ad..f0f9207564ab1 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3100,7 +3100,8 @@ class AnnotatingParser {
if (NextNextToken) {
if (NextNextToken->is(tok::arrow))
return TT_BinaryOperator;
- if (NextNextToken->isPointerOrReference()) {
+ if (NextNextToken->isPointerOrReference() &&
+ !NextToken->isObjCLifetimeQualifier(Style)) {
NextNextToken->setFinalizedType(TT_BinaryOperator);
return TT_BinaryOperator;
}
diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp b/clang/unittests/Format/TokenAnnotatorTest.cpp
index bcb2b6f33d1ad..7982ccb167b53 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -411,6 +411,12 @@ TEST_F(TokenAnnotatorTest, UnderstandsUsesOfStarAndAmp) {
ASSERT_EQ(Tokens.size(), 27u) << Tokens;
EXPECT_TOKEN(Tokens[16], tok::star, TT_BinaryOperator);
EXPECT_TOKEN(Tokens[22], tok::star, TT_BinaryOperator);
+
+ Tokens = annotate("NSError *__autoreleasing *foo;",
+ getLLVMStyle(FormatStyle::LK_ObjC));
+ ASSERT_EQ(Tokens.size(), 7u) << Tokens;
+ EXPECT_TOKEN(Tokens[1], tok::star, TT_PointerOrReference);
+ EXPECT_TOKEN(Tokens[3], tok::star, TT_PointerOrReference);
}
TEST_F(TokenAnnotatorTest, UnderstandsUsesOfPlusAndMinus) {
More information about the cfe-commits
mailing list