llvm / llvm/llvm-project

[clang-format] InsertBraces doesn't work in lambdas after preprocessor directives

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

Description

When `InsertBraces` is enabled, braces are not inserted in lambdas if they are after a preprocessor directive.

Version:
`clang-format version 22.1.5 (https://github.com/llvm/llvm-project 5ea218a153f4d2f815b8244eab3e4b4ba5e00e6c)`

Configuration:
```
BasedOnStyle: Microsoft
BreakBeforeBraces: Allman
InsertBraces: true
```

Input:
```cpp
static void test()
{
if (true) return;

#if true
#endif

if (true) return;

auto inner = []()
{
if (true) return;

auto inner2 = []()
{
if (true) return;
};

#if true
#endif

if (true) return;

auto inner3 = []()
{
if (true) return;
};
};

if (true) return;

#if true
#endif

if (true) return;
}
```

Result:
```cpp
static void test()
{
if (true)
{
return;
}

#if true
#endif

if (true)
{
return;
}

auto inner = []()
{
if (true)
{
return;
}

auto inner2 = []()
{
if (true)
{
return;
}
};

#if true
#endif

if (true)
return;

auto inner3 = []()
{
if (true)
return;
};
};

if (true)
{
return;
}

#if true
#endif

if (true)
{
return;
}
}
```

Expected:
```cpp
static void test()
{
if (true)
{
return;
}

#if true
#endif

if (true)
{
return;
}

auto inner = []()
{
if (true)
{
return;
}

auto inner2 = []()
{
if (true)
{
return;
}
};

#if true
#endif

if (true)
{
return;
}

auto inner3 = []()
{
if (true)
{
return;
}
};
};

if (true)
{
return;
}

#if true
#endif

if (true)
{
return;
}
}
```

In the lambda function `inner`, braces are only inserted before the `#ifdef` directive (which also contains the `inner2` lambda).
After the preprocessor directive, no braces are inserted (which also includes the `inner3` lambda).
Outside the `inner` lambda, everything is formatted correctly.

Contributor guide

Open the contributing guide

Research direction

Start by reproducing the example with clang-format 22.1.5 and the shown InsertBraces configuration, comparing the result with the expected output. Trace how InsertBraces handles preprocessor directives inside nested lambdas, then verify that formatting after the directive matches the expected output and add coverage for this reproducer.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp
Domain
tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
55/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.