Skip to content

Commit 529aa4b

Browse files
committed
[clang-format] Avoid adding space after the name of a function-like macro when the name is a keyword.
Fixes #31086. Before the code: ``` #define if(x) ``` was erroneously formatted to: ``` #define if (x) ``` Reviewed By: HazardyKnusperkeks, owenpan Differential Revision: https://reviews.llvm.org/D118844
1 parent 237eb37 commit 529aa4b

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

clang/lib/Format/UnwrappedLineParser.cpp

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1007,6 +1007,12 @@ void UnwrappedLineParser::parsePPDefine() {
10071007
}
10081008
}
10091009

1010+
// In the context of a define, even keywords should be treated as normal
1011+
// identifiers. Setting the kind to identifier is not enough, because we need
1012+
// to treat additional keywords like __except as well, which are already
1013+
// identifiers.
1014+
FormatTok->Tok.setKind(tok::identifier);
1015+
FormatTok->Tok.setIdentifierInfo(nullptr);
10101016
nextToken();
10111017
if (FormatTok->Tok.getKind() == tok::l_paren &&
10121018
!FormatTok->hasWhitespaceBefore())

clang/unittests/Format/FormatTest.cpp

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1795,6 +1795,18 @@ TEST_F(FormatTest, FormatShortBracedStatements) {
17951795
AllowSimpleBracedStatements);
17961796
}
17971797

1798+
TEST_F(FormatTest, UnderstandsMacros) {
1799+
verifyFormat("#define A (parentheses)");
1800+
verifyFormat("#define true ((int)1)");
1801+
verifyFormat("#define and(x)");
1802+
verifyFormat("#define if(x) x");
1803+
verifyFormat("#define return(x) (x)");
1804+
verifyFormat("#define while(x) for (; x;)");
1805+
verifyFormat("#define xor(x) (^(x))");
1806+
verifyFormat("#define __except(x)");
1807+
verifyFormat("#define __try(x)");
1808+
}
1809+
17981810
TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) {
17991811
FormatStyle Style = getLLVMStyleWithColumns(60);
18001812
Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;

0 commit comments

Comments
 (0)