clang-format: Compound literal in macro is treated as function and wrapped
Given the following C code which takes the address of an expression using a compound literal:
#define getAddr(v, type) &(type){v}
And the .clang-format config file:
IndentWidth: 4
TabWidth: 4
UseTab: Never
---
Language: Cpp
AlignEscapedNewlines: LeftWithLastLine
AllowShortFunctionsOnASingleLine: Empty
BreakBeforeBraces: Attach
It becomes:
#define getAddr(v, type) \
&(type) { \
v \
}
It should be kept the same (not formatted like the above) as it is a compound literal.
Weirdly, clang-format treats & as a function identifier and formats it like a function.
Evidence is shown with:
#define getAddr(v, type) int &(type){v;}
Being formatted as:
#define getAddr(v, type) \
int &(type) { \
v; \
}
Changing AllowShortFunctionsOnASingleLine to All yields:
#define getAddr(v, type) \
&(type) { v }
Which is abnormal since there shouldn't be a break.
On the other hand:
#define ctos(c) (char[2]){c, '\0'}
It is properly formatted. (no change)
@llvm/issue-subscribers-clang-format
Author: None (hueychen27)
And the .clang-format config file:
IndentWidth: 4
TabWidth: 4
UseTab: Never
---
Language: Cpp
AlignEscapedNewlines: LeftWithLastLine
AllowShortFunctionsOnASingleLine: Empty
BreakBeforeBraces: Attach
It becomes:
#define getAddr(v, type) \
&(type) { \
v \
}
It should be kept the same (not formatted like the above) as it is a compound literal.
Weirdly, clang-format treats & as a function identifier and formats it like a function.
Evidence is shown with:
#define getAddr(v, type) int &(type){v;}
Being formatted as:
#define getAddr(v, type) \
int &(type) { \
v; \
}
Changing AllowShortFunctionsOnASingleLine to All yields:
#define getAddr(v, type) \
&(type) { v }
Which is abnormal since there shouldn't be a break.
Hi, I’d like to work on this issue, could you please assign it to me? @hueychen27
Hi, I’d like to work on this issue, could you please assign it to me? @hueychen27
I sent a fix in PR #173771. It includes a regression test and FormatTests pass locally.
For #define getAddr(v, type) int &(type){v;}, I'm not even sure how that's supposed to be formatted since that probably isn't valid C.
For
#define getAddr(v, type) int &(type){v;}, I'm not even sure how that's supposed to be formatted since that probably isn't valid C.
Hi @hueychen27, thanks for pointing that out.
You’re right — the example (#define getAddr(v, type) int &(type){v;}) is not a great test input since it doesn’t form a valid/meaningful C/C++ snippet once expanded, so the expected formatting is unclear.
I’ve removed that case from the regression test and kept the test focused on the original reported pattern.
Tests: FormatTests
A better example would be without the semicolon, but it would only be valid C++:
#define getRef(v, name) int &(name){v}
It formats the same buggy way still. I'm not sure what this syntax is called though (I'm no C++ wizard)