| Issue |
239332
|
| Summary |
[clang-format] InsertBraces changes which if a conditional else belongs to
|
| Labels |
clang-format
|
| Assignees |
|
| Reporter |
and2049
|
With `InsertBraces: true`, inserting braces before a preprocessor conditional can rebind an `else` from the inner `if` to the outer `if`, changing behavior while leaving the output syntactically valid.
### Configuration (`.clang-format`)
```yaml
BasedOnStyle: LLVM
InsertBraces: true
```
### Input
```cpp
void f();
void g();
void h();
void k(bool a, bool b) {
if (a)
if (b)
f();
#if A
g();
#else
else
h();
#endif
}
```
```sh
clang-format test.cpp
```
### Actual output
The function becomes:
```cpp
void k(bool a, bool b) {
if (a) {
if (b) {
f();
}
}
#if A
g();
#else
else {
h();
}
#endif
}
```
With `A` undefined or zero, the `else` now belongs to `if (a)` rather than `if (b)`.
When `a` is false, the formatted code calls `h()` although the original calls neither function.
When `a` is true and `b` is false, the original calls `h()` but the formatted code does not.
### Expected behavior
Preserve the inner `if`/`else` association. One safe result is to insert braces around the inner branches and leave the outer `if` unbraced:
```cpp
void k(bool a, bool b) {
if (a)
if (b) {
f();
}
#if A
g();
#else
else {
h();
}
#endif
}
```
With `A=0`, the original code is equivalent to:
```cpp
if (a) {
if (b) {
f();
} else {
h();
}
}
```
With `A=1`, the call to `g()` remains unconditional:
```cpp
if (a) {
if (b) {
f();
}
}
g();
```
The input, actual output and proposed safe output all compile with `A` undefined, zero and one. Runtime comparisons across all four `a`/`b` combinations confirm that the proposed output preserves behavior in every configuration, while the actual output changes behavior when `A` is undefined or zero.
Related to #224942, but this reproducer changes the `else` association rather than producing unmatched braces.
Reproduced on main at `71926eeb7dc3` (`clang-format version 24.0.0git`, assertions enabled) and 21.1.8.
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs