Fixes https://github.com/llvm/llvm-project/issues/53576.
There was an inconsistency in formatting of delete expressions.
Before:
```
delete (void*)a;
delete[](void*) a;
```
After this patch:
```
delete (void*)a;
delete[] (void*)a;
```
Reviewed By: HazardyKnusperkeks, owenpan
Differential Revision: https://reviews.llvm.org/D119117
- Add or remove empty lines surrounding union blocks.
- Fixes https://github.com/llvm/llvm-project/issues/53229, in which
keywords like class and struct in a line ending with left brace or
whose next line is left brace only, will be falsely recognized as
definition line, causing extra empty lines inserted surrounding blocks
with no need to be formatted.
Reviewed By: MyDeveloperDay, curdeius, HazardyKnusperkeks, owenpan
Differential Revision: https://reviews.llvm.org/D119067
The l_brace token in a macro definition should not be set to
TT_FunctionLBrace.
This patch could have fixed#42087.
Differential Revision: https://reviews.llvm.org/D118969
The second space in `void foo() &` is always produced by clang-format,
and isn't evidence of any particular style.
Before this patch, it was considered evidence of PAS_Right, because
there is a space before a pointerlike ampersand.
This caused the following code to have "unstable" pointer alignment:
void a() &;
void b() &;
int *x;
PAS_Left, Derive=false would produce 'int* x' with other lines unchanged.
But subsequent formatting with Derive=true would produce 'int *x' again.
Differential Revision: https://reviews.llvm.org/D118921
* Give I[1] and I[-1] a name:
- Easier to understand
- Easier to debug (since you don't go through operator[] everytime)
* TheLine->First != TheLine->Last follows since last is a l brace and
first isn't.
* Factor the check for is(tok::l_brace) out.
* Drop else after return.
Differential Revision: https://reviews.llvm.org/D115060
This commit changes the condition of requiring comment to start with
alphanumeric characters to make no change only for a certain set of
characters, currently horizontal whitespace and punctuation characters,
to support wider set of leading characters unrelated to documentation
generation directives.
Reviewed By: HazardyKnusperkeks
Differential Revision: https://reviews.llvm.org/D118869
Fixes https://github.com/llvm/llvm-project/issues/31592.
This commits enables lexing of digraphs in C++11 and onwards.
Enabling them in C++03 is error-prone, as it would unconditionally treat sequences like "<:" as digraphs, even if they are followed by a single colon, e.g. "<::" would be treated as "[:" instead of "<" followed by "::". Lexing in C++11 doesn't have this problem as it looks ahead the following token.
The relevant excerpt from Lexer::LexTokenInternal:
```
// C++0x [lex.pptoken]p3:
// Otherwise, if the next three characters are <:: and the subsequent
// character is neither : nor >, the < is treated as a preprocessor
// token by itself and not as the first character of the alternative
// token <:.
```
Also, note that both clang and gcc turn on digraphs by default (-fdigraphs), so clang-format should match this behaviour.
Reviewed By: MyDeveloperDay, HazardyKnusperkeks, owenpan
Differential Revision: https://reviews.llvm.org/D118706
Fixes https://github.com/llvm/llvm-project/issues/52772.
This patch fixes the formatting of the code:
```
auto aaaaaaaaaaaaaaaaaaaaa = {};
auto b = g([] {
return;
});
```
which should be left as is, but before this patch was formatted to:
```
auto aaaaaaaaaaaaaaaaaaaaa = {};
auto b = g([] {
return;
});
```
Reviewed By: MyDeveloperDay, HazardyKnusperkeks
Differential Revision: https://reviews.llvm.org/D115972
Fixes https://github.com/llvm/llvm-project/issues/34626.
Before, the include sorter would break the code:
```
#include <stdio.h>
#include <stdint.h> /* long
comment */
```
and change it into:
```
#include <stdint.h> /* long
#include <stdio.h>
comment */
```
This commit handles only the most basic case of a single block comment on an include line, but does not try to handle all the possible edge cases with multiple comments.
Reviewed By: HazardyKnusperkeks
Differential Revision: https://reviews.llvm.org/D118627
Fixes https://github.com/llvm/llvm-project/issues/53441.
Expected code:
```
/**/ //
int a; //
```
was before misformatted to:
```
/**/ //
int a; //
```
Because the "remaining length" (after the starting `/*`) of an empty block comment `/**/` was computed to be 0 instead of 2.
Reviewed By: MyDeveloperDay, HazardyKnusperkeks, owenpan
Differential Revision: https://reviews.llvm.org/D118475
SortJavaScriptImports attempts to set its currently parsed token to an
invalid token when it reaches the end of the line. However in doing so,
it used a `FormatToken`, which contains a `Token Tok`. `Token` does not
have a constructor, so its fields start out as uninitialized memory.
`Token::startToken()` initializes all fields. Calling it in
`JavaScriptImportSorter`'s constructor thus fixes the problem.
Differential Revision: https://reviews.llvm.org/D118448
import X = A.B.C;
Previously, these were unhandled and would terminate import sorting.
With this change, aliases sort as their own group, coming last after all
other imports.
Aliases are not sorted within their group, as they may reference each
other, so order is significant.
This reverts commit f750c3d95a. It fixes
the msan issue by not parsing past the end of the line when handling
import aliases.
Differential Revision: https://reviews.llvm.org/D118446
Fixes https://github.com/llvm/llvm-project/issues/53430.
Initially, I had a quick and dirty approach, but it led to a myriad of special cases handling comments (that may add unwrapped lines).
So I added TT_RecordLBrace type annotations and it seems like a much nicer solution.
I think that in the future it will allow us to clean up some convoluted code that detects records.
Reviewed By: MyDeveloperDay, HazardyKnusperkeks
Differential Revision: https://reviews.llvm.org/D118337
Users can define aliases for long symbols using import aliases:
import X = A.B.C;
Previously, these were unhandled and would terminate import sorting.
With this change, aliases sort as their own group, coming last after all
other imports.
Aliases are not sorted within their group, as they may reference each
other, so order is significant.
Revision URI: https://reviews.llvm.org/D118361
- Fixes https://github.com/llvm/llvm-project/issues/53227 that wrongly
indents multiline comments
- Fixes wrong detection of single-line opening braces when used along
with those only opening scopes, causing crashes due to duplicated
replacements on the same token:
void foo()
{
{
int x;
}
}
- Fixes wrong recognition of first line of definition when the line
starts with block comment, causing crashes due to duplicated
replacements on the same token for this leads toward skipping the line
starting with inline block comment:
/*
Some descriptions about function
*/
/*inline*/ void bar() {
}
- Fixes wrong recognition of enum when used as a type name rather than
starting definition block, causing crashes due to duplicated
replacements on the same token since both actions for enum and for
definition blocks were taken place:
void foobar(const enum EnumType e) {
}
- Change to use function keyword for JavaScript instead of comparing
strings
- Resolves formatting conflict with options EmptyLineAfterAccessModifier
and EmptyLineBeforeAccessModifier (prompts with --dry-run (-n) or
--output-replacement-xml but no observable change)
- Recognize long (len>=5) uppercased name taking a single line as return
type and fix the problem of adding newline below it, with adding new
token type FunctionLikeOrFreestandingMacro and marking tokens in
UnwrappedLineParser:
void
afunc(int x) {
return;
}
TYPENAME
func(int x, int y) {
// ...
}
- Remove redundant and repeated initialization
- Do no change to newlines before EOF
Reviewed By: MyDeveloperDay, curdeius, HazardyKnusperkeks
Differential Revision: https://reviews.llvm.org/D117520
LLVM Programmer’s Manual strongly discourages the use of `std::vector<bool>` and suggests `llvm::BitVector` as a possible replacement.
Currently, some users of `std::vector<bool>` cannot switch to `llvm::BitVector` because it doesn't implement the `pop_back()` and `back()` functions.
To enable easy transition of `std::vector<bool>` users, this patch implements `llvm::BitVector::pop_back()` and `llvm::BitVector::back()`.
Reviewed By: dexonsmith
Differential Revision: https://reviews.llvm.org/D117115
This factors out a pattern that comes up from time to time.
Reviewed By: MyDeveloperDay, HazardyKnusperkeks, owenpan
Differential Revision: https://reviews.llvm.org/D117769
Fixes https://github.com/llvm/llvm-project/issues/44601.
This patch handles a bug when parsing a below example code :
```
template <class> class S;
template <class T> bool operator<(S<T> const &x, S<T> const &y) {
return x.i < y.i;
}
template <class T> class S {
int i = 42;
friend bool operator< <>(S const &, S const &);
};
int main() { return S<int>{} < S<int>{}; }
```
which parse `< <>` as `<< >`, not `< <>` in terms of tokens as discussed in discord.
1. Add a condition in `tryMergeLessLess()` considering `operator` keyword and `>`
2. Force to leave a whitespace between `tok::less` and a template opener
3. Add unit test
Reviewed By: MyDeveloperDay, curdeius
Differential Revision: https://reviews.llvm.org/D117398
This style is similar to AlwaysBreak, but places closing brackets on new lines.
For example, if you have a multiline parameter list, clang-format currently only supports breaking per-parameter, but places the closing bracket on the line of the last parameter.
Function(
param1,
param2,
param3);
A style supported by other code styling tools (e.g. rustfmt) is to allow the closing brackets to be placed on their own line, aiding the user in being able to quickly infer the bounds of the block of code.
Function(
param1,
param2,
param3
);
For prior work on a similar feature, see: https://reviews.llvm.org/D33029.
Note: This currently only supports block indentation for closing parentheses.
Differential Revision: https://reviews.llvm.org/D109557
Fixes https://github.com/llvm/llvm-project/issues/24784.
With config:
```
AllowShortFunctionsOnASingleLine: Inline
NamespaceIndentation: All
```
The code:
```
namespace Test
{
void f()
{
return;
}
}
```
was incorrectly formatted to:
```
namespace Test
{
void f() { return; }
}
```
since the function `f` was considered being inside a class/struct/record.
That's because the check was simplistic and only checked for a non-zero indentation level of the line starting `f`.
Reviewed By: MyDeveloperDay, HazardyKnusperkeks
Differential Revision: https://reviews.llvm.org/D117142
https://github.com/llvm/llvm-project/issues/27037
Sorry its taken so long to get to this issue! (got it before it hit its 6th birthday!)
```
void operator delete(void *foo)ATTRIB;
```
(void *foo) is incorrectly determined to be a C-Style Cast resulting in the space being removed after the ) and before the attrib, due to the detection of
```
delete (A* )a;
```
The following was previously unaffected
```
void operator new(void *foo) ATTRIB;
```
Fixes#27037
Reviewed By: curdeius, HazardyKnusperkeks
Differential Revision: https://reviews.llvm.org/D116920
Fixes https://github.com/llvm/llvm-project/issues/52976.
- Make no formatting for macros
- Attach comment with definition headers
- Make no change on use of empty lines at block start/end
- Fix misrecognition of keyword namespace
Differential Revision: https://reviews.llvm.org/D116663
Reviewed By: MyDeveloperDay, HazardyKnusperkeks, curdeius
I think the deque was chosen because of a better push_front, but in
combination with llvm::reverse the push_back'ed vector should be the
better choice.
Differential Revision: https://reviews.llvm.org/D115064
This change adds an option AfterOverloadedOperator in SpaceBeforeParensOptions to add a space between overloaded operator and opening parentheses in clang-format.
Reviewed By: MyDeveloperDay, curdeius, HazardyKnusperkeks
Differential Revision: https://reviews.llvm.org/D116283
* Give I[1] and I[-1] a name:
- Easier to understand
- Easier to debug (since you don't go through operator[] everytime)
* TheLine->First != TheLine->Last follows since last is a l brace and
first isn't.
* Factor the check for is(tok::l_brace) out.
* Drop else after return.
Differential Revision: https://reviews.llvm.org/D115060
This commit resolves GitHub issue #45895 (Bugzilla #46550), to
add or remove empty line between definition blocks including
namespaces, classes, structs, enums and functions.
Reviewed By: MyDeveloperDay, curdeius, HazardyKnusperkeks
Differential Revision: https://reviews.llvm.org/D116314
My team has a vendetta against lines ending with an open parenthesis, thought it might be useful for others too 😊
Reviewed By: HazardyKnusperkeks, curdeius
Differential Revision: https://reviews.llvm.org/D116170
There is some similar looking code in `TokenAnnotator.cpp` but given that I've
never worked on clang-format before I don't know what the purpose of that code
is and how it's related to `UnwrappedLineParser.cpp`.
Either way, it fixes clang-format with `BraceWrapping.AfterEnum=true` and
`AllowShortEnumsOnASingleLine=false` to behave like the documentation says.
Before this patch:
```
enum
{
A,
B
} myEnum;
```
After this patch:
```
enum {
A,
B
} myEnum;
```
According to the unittests which I had to modify this would change the LLVM
style. Please evaluate if you want to change the defaults or if you consider
the current style a bug.
Reviewed By: curdeius, HazardyKnusperkeks
Differential Revision: https://reviews.llvm.org/D106349
https://github.com/llvm/llvm-project/issues/52881
It seems that clang-format off/on is not being honoured in regard to adding spaces.
My understanding of clang-format off/on is that it marks the token as finalized based on whether formatting is currently enabled or disabled.
This was causing a space to be added between the `<` and `<<` in the Cuda kernel `foo<<<1, 1>>>();`
This if doesn't solve this actual issue but ensure that clang-format is at least honoured.
Reviewed By: curdeius, owenpan
Differential Revision: https://reviews.llvm.org/D116494
This diff extends the -style=file option to allow a config file to be specified explicitly. This is useful (for instance) when adding IDE commands to reformat code to a personal style.
Usage: `clang-format -style=file:<path/to/config/file> ...`
Reviewed By: HazardyKnusperkeks, curdeius, MyDeveloperDay, zwliew
Differential Revision: https://reviews.llvm.org/D72326
Currently, we are unable to inherit from a chain of parent configs where the outermost parent config has `BasedOnStyle: InheritParentConfig` set. This patch adds a test case for this scenario, and adds support for it.
To illustrate, suppose we have the following directory structure:
```
- e/
|- .clang-format (BasedOnStyle: InheritParentConfig) <-- outermost config
|- sub/
|- .clang-format (BasedOnStyle: InheritParentConfig)
|- sub/
|- .clang-format (BasedOnStyle: InheritParentConfig)
|- code.cpp
```
Now consider what happens when we run `clang-format --style=file /e/sub/sub/code.cpp`.
Without this patch, on a release build, only the innermost config will be applied. On a debug build, clang-format crashes due to an assertion failure.
With this patch, clang-format behaves as we'd expect, applying all 3 configs.
Reviewed By: HazardyKnusperkeks, curdeius
Differential Revision: https://reviews.llvm.org/D116371
Single-variant enums were still getting placed on a single line
even when AllowShortEnumsOnASingleLine was false. This fixes that
by checking that setting when looking to merge lines.
Differential Revision: https://reviews.llvm.org/D116188
Move the handling of brace wrapping after => from unwrapped line
parser to token annotator and clean up the parser.
Differential Revision: https://reviews.llvm.org/D115967
It appears that this regressed the formatting of initializer lists in some
cases, see comments on https://reviews.llvm.org/D114583. I'll follow-up
by adding regression tests for these.
This reverts commit c41b3b0fa0.
Reviewed By: MyDeveloperDay
Differential Revision: https://reviews.llvm.org/D116000
https://github.com/llvm/llvm-project/issues/49804
Interaction between IndentExternBlock and AfterExternBlock means you cannot have AfterExternBlock = true and IndentExternBlock = NoIndent/Indent
This patch resolves that
```
BraceWrapping:
AfterExternBlock: true
IndentExternBlock: AfterExternBlock
```
Fixes: #49804
Reviewed By: HazardyKnusperkeks, curdeius, owenpan
Differential Revision: https://reviews.llvm.org/D115879
The alignment fix introduced by https://reviews.llvm.org/D104388 caused a regression whereby formatting of code that follows the lambda block is incorrect i.e. separate expressions are put on the same line.
Differential Revision: https://reviews.llvm.org/D115738
https://github.com/llvm/llvm-project/issues/52715Fixes#52715
`AllowShortBlocksOnASingleLine` seems to never be checked for "Empty" as such if its used it will be considered "Always" as we only ever check `AllowShortBlocksOnASingleLine != Never`
This impacts C++ as well as C# hence the slightly duplicated test.
Reviewed By: curdeius, jbcoe
Differential Revision: https://reviews.llvm.org/D115794
https://github.com/llvm/llvm-project/issues/48642
clang-format does not respect raw string literals when sorting includes
```
const char *RawStr = R"(
)";
```
Running clang-format over with SortIncludes enabled transforms this code to:
```
const char *RawStr = R"(
)";
```
The following code tries to minimize this impact during IncludeSorting, by treating R"( and )" as equivalent of // clang-format off/on
Reviewed By: HazardyKnusperkeks, curdeius
Differential Revision: https://reviews.llvm.org/D115168Fixes#48642
Responding to a Discord call to help {D113977} and heavily inspired by the unlanded {D34225} add some support to help coroutinues from not being formatted from
```for co_await(auto elt : seq)```
to
```
for
co_await(auto elt : seq)
```
Because of the dominance of clang-format in the C++ community, I don't think we should make it the blocker that prevents users from embracing the newer parts of the standard because we butcher the layout of some of the new constucts.
Reviewed By: HazardyKnusperkeks, Quuxplusone, ChuanqiXu
Differential Revision: https://reviews.llvm.org/D114859
Make sure we do not try to change line comments that are non-regular, i.e. do
not start with "//" or "#". This can for example happen when "//" is
broken into two lines with an escaped newline.
Previously, clang-format would not correctly identify preprocessor
directives directly following a conflict marker, which would result in
violating the formatter's invariants.
The provided test fails in assert mode before this change.
{D110833} regressed behavior of spaces before parentheses for operators, this revision reverts that so that operators are handled as they were before.
I think in hindsight it was a mistake to try and consume operator behaviour in with the function behaviour, I think Operators can be considered a special style. Its seems the code is getting confused as to if this is a function declaration or definition.
I think latterly we can consider adding an operator parentheses specific custom option but this should have been explicitly called out as it can impact projects.
Reviewed By: HazardyKnusperkeks, curdeius
Differential Revision: https://reviews.llvm.org/D114696
https://bugs.llvm.org/show_bug.cgi?id=52517
clang-format is butchering modules, this could easily become a barrier to entry for modules given clang-formats wide spread use.
Prevent the following from adding spaces around the `:` (cf was considering the ':' as an InheritanceColon)
Reviewed By: HazardyKnusperkeks, owenpan, ChuanqiXu
Differential Revision: https://reviews.llvm.org/D114151
https://bugs.llvm.org/show_bug.cgi?id=52595
missing space between `T(&&)` but not between `T (&` due to && being incorrectly thought of as `UnaryOperator` rather than `PointerOrReference`
```
int operator()(T (&)[N]) { return 0; }
int operator()(T(&&)[N]) { return 1; }
```
Existing Unit tests are changed because actually I think they are originally incorrect, and are inconsistent with the (&) cases that are 4 or 5 lines above them.
Reviewed By: curdeius
Differential Revision: https://reviews.llvm.org/D114519
https://bugs.llvm.org/show_bug.cgi?id=47936
Using the MultiLine setting for BraceWrapping.AfterControlStatement appears to disable AllowShortFunctionsOnASingleLine, even in cases without any control statements
Reviewed By: HazardyKnusperkeks, curdeius
Differential Revision: https://reviews.llvm.org/D114521
Make all code go through FormatTokenSource instead of going around it, which
makes changes to TokenSource brittle.
Add LLVM_DEBUG in FormatTokenSource to be able to follow the token stream.
When building clang-format with -Wall on Visual Studio 20119 we see the following, prevent this the only -Wall error
```
..FormatTokenLexer.cpp(45) : warning C4868: compiler may not enforce left-to-right evaluation order in braced initializer list
```
Reviewed By: HazardyKnusperkeks
Differential Revision: https://reviews.llvm.org/D113844
1. IndexTokenSource::getNextToken cannot return nullptr; some code was
still written assuming it can; make getNextToken more resilient against
incorrect input and fix its call-sites.
2. Change various asserts that can happen due to user provided input to
conditionals in the code.
Makes clang-format bail out if an in-memory source file with an
unsupported BOM is handed in instead of creating source locations that
are violating clang's assumptions.
In the future, we should add support to better transport error messages
like this through clang-format instead of printing to stderr and not
creating any changes.