llvm / llvm/llvm-project

[clang-format] Incorrect spacing with `AlignArrayOfStructures: Left` in parenthesized lists with trailing commas inside brace initializers

Open
#165,932 1 comment 0 reactions 0 assignees View on GitHub
clang-format
Dominant language
LLVM
Stars
40.5k
Forks
18.7k
PR merge metrics
PR metrics pending

Description

With `AlignArrayOfStructures: Left` enabled, clang-format adds spurious spaces to certain expressions inside nested brace initializers. It's kind of hard to explain precisely, so I made a simplified example:

Running `clang-format -style="{AlignArrayOfStructures: Left}"` on

```c++
#define MACRO(a, ...) (a)

struct TestStruct {
int a1[1];
int a2[1];
} test = {
{
MACRO(1, 3, 235, 12, -1, 99, 0),
},
{
MACRO(8, 9, 5, 1, 62, 5, 101),
},
};
```

results in

```c++
#define MACRO(a, ...) (a)

struct TestStruct {
int a1[1];
int a2[1];
} test = {
{
MACRO(1, 3, 235, 12, -1, 99, 0),
},
{
MACRO(8, 9, 5, 1, 62, 5, 101),
},
};
```

I'm not sure what it *should* look like, but definitely not that.

As far as I can tell, this occurs when:
- each inner macro invocation (or parenthesized list) has the same number of comma-separated arguments, and
- each inner list is followed by a trailing comma.

If the lists have different numbers of elements, it seems `AlignArrayOfStructures` won't touch it—so they just end up separated by single spaces.

This also occurs when using designated initializers (which is how I originally encountered the issue).

I was able to reproduce this issue using:
- the official LLVM 21.1.4 release for 64-bit Windows
- whatever version is bundled with the VS Code C/C++ extension
- Debian's clang-format 19.1.7 (`Debian clang-format version 19.1.7 (7)`)

Here's an example file that might make the required conditions clearer: [clang-format_spacing_example.txt](https://github.com/user-attachments/files/23277478/clang-format_spacing_example.txt)
(GitHub wouldn't let me upload it with a `cpp` extension. It contains some bonus strange behavior at the end that I didn't have time to look into.)

Contributor guide

Open the contributing guide

Research direction

Start by running clang-format with AlignArrayOfStructures: Left on the C++ reproducer in the issue and compare the current output with the reported input. Investigate the formatting behavior for nested brace initializers, parenthesized lists, trailing commas, and designated initializers; done means the formatter no longer inserts spurious alignment spaces.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp
Domain
tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.