Skip to content

Commit

Permalink
[clang-format] Avoid adding space after the name of a function-like m…
Browse files Browse the repository at this point in the history
…acro 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
  • Loading branch information
mkurdej committed Feb 3, 2022
1 parent 237eb37 commit 529aa4b
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
6 changes: 6 additions & 0 deletions clang/lib/Format/UnwrappedLineParser.cpp
Expand Up @@ -1007,6 +1007,12 @@ void UnwrappedLineParser::parsePPDefine() {
}
}

// In the context of a define, even keywords should be treated as normal
// identifiers. Setting the kind to identifier is not enough, because we need
// to treat additional keywords like __except as well, which are already
// identifiers.
FormatTok->Tok.setKind(tok::identifier);
FormatTok->Tok.setIdentifierInfo(nullptr);
nextToken();
if (FormatTok->Tok.getKind() == tok::l_paren &&
!FormatTok->hasWhitespaceBefore())
Expand Down
12 changes: 12 additions & 0 deletions clang/unittests/Format/FormatTest.cpp
Expand Up @@ -1795,6 +1795,18 @@ TEST_F(FormatTest, FormatShortBracedStatements) {
AllowSimpleBracedStatements);
}

TEST_F(FormatTest, UnderstandsMacros) {
verifyFormat("#define A (parentheses)");
verifyFormat("#define true ((int)1)");
verifyFormat("#define and(x)");
verifyFormat("#define if(x) x");
verifyFormat("#define return(x) (x)");
verifyFormat("#define while(x) for (; x;)");
verifyFormat("#define xor(x) (^(x))");
verifyFormat("#define __except(x)");
verifyFormat("#define __try(x)");
}

TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) {
FormatStyle Style = getLLVMStyleWithColumns(60);
Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
Expand Down

0 comments on commit 529aa4b

Please sign in to comment.