Commit Graph

2608 Commits

Author SHA1 Message Date
Owen Pan e33243c950 [clang-format] Link the braces of a block in UnwrappedLineParser
This includes TT_MacroBlockBegin and TT_MacroBlockEnd as well.

We can no longer use MatchingParen of FormatToken as an indicator
to mark optional braces. Instead, we directly set Optional of an
l_brace first and reset it later if it turns out that the braces
are not optional.

Also added a test case for deeply nested loops.

Differential Revision: https://reviews.llvm.org/D139257
2022-12-04 12:01:26 -08:00
Maíra Canal ad83bead3d [clang-format] Don't move comments if AlignTrailingComments: Leave
For comments that start after a new line, currently, the comments are
being indented. This happens because the OriginalWhitespaceRange
considers newlines on the range. Therefore, when AlignTrailingComments:
Kind: Leave, deduct the number of newlines before the token to calculate
the number of spaces for trailing comments.

Fixes #59203.

Differential Revision: https://reviews.llvm.org/D139029
2022-12-01 16:07:06 -08:00
Manuel Klimek ca8c6156f2 Fix test output regression from ee88c0cf09.
The unused variable fix also remove the test output of the tokens
that do not match, making debugging tests harder. Undo the semantic
changes of the build fix.
2022-11-25 13:53:34 +00:00
Sam McCall a72609cabe [Format] Don't crash on mismatched brackets 2022-11-24 15:14:06 +01:00
Owen Pan 4daeb8c733 [clang-format] Fix a crash due to dereferencing null MatchingParen
Fixes #59089.

Differential Revision: https://reviews.llvm.org/D138371
2022-11-21 12:33:51 -08:00
Björn Schäpers 5ba5f7c46c [clang-format][NFC] Removed unused include 2022-11-21 13:24:19 +01:00
Noah Goldstein 92bccf5d3d [clang-format] Don't use PPIndentWidth inside multi-line macros
Differential Revision: https://reviews.llvm.org/D137181
2022-11-19 23:53:48 -08:00
Emilia Dreamer 48a932e13e
[clang-format] Remove special case for kw_operator when aligning decls
This change breaks no existing tests but does fix the linked issue.
Declarations of operator overloads are annotated with
`TT_FunctionDeclarationName` on the `operator` keyword, which is already
being checked for when aligning, so the extra `kw_operator` doesn't seem
to be necessary. (just for reference, it was added in
rG92b397fb9d55ccdf4632c2b1b15b4a0ee417cf74 / 92b397fb9d)

Fixes https://github.com/llvm/llvm-project/issues/55733

Reviewed By: HazardyKnusperkeks, owenpan

Differential Revision: https://reviews.llvm.org/D137223
2022-11-17 11:38:28 +02:00
Emilia Dreamer df6f4b8513
[clang-format] Defer formatting of operator< to honor paren spacing
I'm not exactly sure what the intent of that section of
`spaceRequiredBetween` is doing, it seems to handle templates and <<,
but the part which adds spaces before parens is way later, as part
of `spaceRequiredBeforeParens`.

Fixes https://github.com/llvm/llvm-project/issues/58821

Reviewed By: HazardyKnusperkeks, owenpan, MyDeveloperDay

Differential Revision: https://reviews.llvm.org/D137474
2022-11-17 11:38:21 +02:00
Björn Schäpers 617277e7cb [clang-format][NFC] Moved configuration parsing tests in own file
I want to reduce the size of ForatTest.cpp with its still wopping 25k
lines it is a burden on the compiler and editor (mine is clangd
powered).

This are tests which are really serving a different purpose than
formatting.

I've copied the code and made the following changes:
- Dropped the ; at the end of some macros, all macro "invocations"
  already have their own ;.
- Dropped the _F, we don't need a fxiture here.

Differential Revisison: https://reviews.llvm.org/D137823
2022-11-16 07:02:09 +01:00
Micah Weston e864ac6945 [clang-format] Treats &/&& as reference when followed by ',' or ')'
Ran into an issue where function declarations inside function
scopes or uses of sizeof inside a function would treat the && in
'sizeof(Type &&)' as a binary operator.

Attempt to fix this by assuming reference when followed by ',' or
')'. Also adds tests for these.

Also hit an edge case in another test that treated "and" the same
as "&&" since it parses as C++. Changed the "and" to "also" so it
is no longer a keyword.

Fixes #58923.

Differential Revision: https://reviews.llvm.org/D137755
2022-11-12 00:58:58 -08:00
Owen Pan 96e23906b5 [clang-format] Correctly annotate function names before attributes
Fixes #58827.

Differential Revision: https://reviews.llvm.org/D137486
2022-11-12 00:40:46 -08:00
Anastasiia Lukianenko f6b252978c [clang-format] Add BreakBeforeInlineASMColon configuration
If true, colons in ASM parameters will be placed after line breaks.

true:
asm volatile("string",
                     :
                     : val);

false:
asm volatile("string", : : val);

Differential Revision: https://reviews.llvm.org/D91950
2022-11-10 22:31:09 +01:00
Björn Schäpers 41a09a07ce [clang-format][NFCish] Alphabetical sort Format.(h|pp)
I've:
- Sorted the members of FormatStyle alphabetical. The enums and structs
  are kept close to the member.
- Sorted the yaml io functions, based on the type they operate on.
- Sorted the initializers in getLLVMStyle(), except that penalities are
  kept at the end.
- Sorted the io of FormatStyle, this changes the --dump-config behavior.
- Moved the deprecated options into the only input case, this also
  changes --dump-config, it does not put the not directly used options
  in the .clang-format anymore.
- Sorted the comparisons in operator==.
- Added WhiteSpaceMacros in operator==, I've not actively looked if all
  other members are compared.
- This showed flawed tests (or in my opinion a flawed io operation, but
  that is another discussion and change).

Differential Revision: https://reviews.llvm.org/D137409
2022-11-08 21:46:15 +01:00
Tobias Hieta 70de684d44
[clang-format] Handle object instansiation in if-statements
Before this patch code like this:

```
if (Class* obj{getObject()}) { }
```

would be mis-formated since the * would be annotated as a
binaryoperator.

This patch changes the * to become a PointerOrReference instead
and fixes the formatting issues.

Reviewed By: HazardyKnusperkeks

Differential Revision: https://reviews.llvm.org/D137327
2022-11-07 08:34:57 +01:00
Björn Schäpers f97639ce13 [clang-format] Don't misannotate in CTor init list
They were annotated with TrailingAnnotation, which they are not. And
that resulted in some quirky formatting in some cases.

Differential Revision: https://reviews.llvm.org/D136635
2022-11-03 13:08:48 +01:00
Björn Schäpers cdbe296853 [clang-format] Fix lambda formatting in conditional
Without the patch UnwrappedLineFormatter::analyzeSolutionSpace just ran
out of possible formattings and would put everything just on one line.
The problem was that the the line break was forbidden, but putting the
conditional colon on the same line is also forbidden.

Differential Revision: https://reviews.llvm.org/D135918
2022-11-03 13:08:14 +01:00
Owen Pan 117d792f35 [clang-format] Don't skip #else/#elif of #if 0
Fixes #58188.

Differential Revision: https://reviews.llvm.org/D137052
2022-11-02 13:32:08 -07:00
Yusuke Kadowaki 3edc1210a4 [clang-format] Adds a formatter for aligning trailing comments over empty lines
This patch addresses https://github.com/llvm/llvm-project/issues/19756

Reviewed By: MyDeveloperDay, HazardyKnusperkeks

Differential Revision: https://reviews.llvm.org/D132131
2022-10-30 12:22:39 +00:00
sstwcw d5be1550f1 [clang-format] Don't crash on malformed preprocessor conditions
Previously the program would crash on this input:

```
#else
#if X
```

The problem was that in `parsePPElse`, `PPBranchLevel` would be
incremented when the first `#else` gets parsed, but `PPLevelBranchCount`
and `PPLevelBranchIndex` would not be updated together.

I found the problem when working on D135740.

Differential Revision: https://reviews.llvm.org/D135972
2022-10-30 02:18:58 +00:00
owenca 30ea3fcc4c [clang-format][NFC] Move BracesRemover tests out of FormatTest.cpp
Differential Revision: https://reviews.llvm.org/D136830
2022-10-28 23:44:41 -07:00
owenca 17059753f1 [clang-format] Move InsertBraces unit tests out of FormatTest.cpp
Also add line range examples from #58161.

Differential Revision: https://reviews.llvm.org/D136658
2022-10-27 01:29:31 -07:00
Emilia Dreamer dce5bb9a6f
[clang-format] Correctly annotate UDLs as OverloadedOperator
While the opening parenthesis of an user-defined literal operator was
correctly annotated as OverloadedOperatorLParen, the "" and its suffix
wasn't annotated as OverloadedOperator.

Fixes https://github.com/llvm/llvm-project/issues/58035

Differential Revision: https://reviews.llvm.org/D134853
2022-10-25 20:11:52 +03:00
Tobias Hieta fd1d93db71
[clang-format] Mark pragma region lines as StringLiterals
In our code-base we auto-generate pragma regions the regions
look like method signatures like:

`#pragma region MYREGION(Foo: bar)`

The problem here was that the rest of the line after region
was not marked as stringliteral as in the case of pragma mark
so clang-format tried to change the formatting based on the
method signature.

Added test and mark it similar as pragma mark.

Reviewed By: owenpan

Differential Revision: https://reviews.llvm.org/D136336
2022-10-25 09:59:39 +02:00
Danil Sidoruk 9c422ab7ce
[clang-format] Add option for aligning requires clause body
Adds an option whether requires clause body should be aligned with
the `requires` keyword.
This option is now the default, both without configuration and in LLVM
style.

Fixes https://github.com/llvm/llvm-project/issues/56283

Differential Revision: https://reviews.llvm.org/D129443

Co-authored-by: Emilia Dreamer <emilia@rymiel.space>
2022-10-21 10:42:45 +03:00
Joseph Huber 037669de8b [clang-format] Do not parse certain characters in pragma directives
Currently, we parse lines inside of a compiler `#pragma` the same way we
parse any other line. This is fine for some cases, like separating
expressions and adding proper spacing, but in others it causes some poor
results from miscategorizing some tokens.

For example, the OpenMP offloading uses certain clauses that contain
special characters like `map(tofrom : A[0:N])`. This will be formatted
poorly as it will be split between lines on the first colon.
Additionally the subscript notation will lead to poor spacing. This can
be seen in the OpenMP tests as the automatic clang formatting with
inevitably ruin the formatting.

For example, the following contrived example will be formatted poorly.
```
#pragma omp target teams distribute collapse(2) map(to: A[0 : M * K])  \
    map(to: B[0:K * N]) map(tofrom:C[0:M*N]) firstprivate(Alpha) \
    firstprivate(Beta) firstprivate(X) firstprivate(D) firstprivate(Y) \
    firstprivate(E) firstprivate(Z) firstprivate(F)
```
This results in this when formatted, which is far from ideal.
```
#pragma omp target teams distribute collapse(2) map(to                         \
                                                    : A [0:M * K])             \
    map(to                                                                     \
        : B [0:K * N]) map(tofrom                                              \
                           : C [0:M * N]) firstprivate(Alpha)                  \
        firstprivate(Beta) firstprivate(X) firstprivate(D) firstprivate(Y)     \
            firstprivate(E) firstprivate(Z) firstprivate(F)
```

This patch seeks to improve this by adding extra logic where the parsing goes
awry. This is primarily caused by the colon being parsed as an inline-asm
directive and the brackes an objective-C expressions. Also the line gets
indented every single time the line is dropped.

This doesn't implement true parsing handling for OpenMP statements.

Reviewed By: HazardyKnusperkeks

Differential Revision: https://reviews.llvm.org/D136100
2022-10-18 16:38:19 -05:00
Emilia Dreamer 94215d2b21
[clang-format] Correctly annotate star/amp in function pointer params
Inside the arguments part of a function pointer declaration,
`determineStarAmpUsage` results in a binary operator rather than
pointers, because said parens are assumed to be an expression.

This patch correctly marks the argument parens of a function
pointer type as not an expression. Note that this fix already
existed for Objective-C blocks as part of f1f267b447.
As Objective-C blocks and C/C++ function pointers share a lot
of the same logic, that fix also makes sense here.

Fixes https://github.com/llvm/llvm-project/issues/31659

Differential Revision: https://reviews.llvm.org/D135707
2022-10-18 08:17:23 +03:00
Jacob Abraham b0758f62af [clang-format] Fix mis-attributing preprocessor directives to macros
This solves the issue where a case statement inside a macro greedily
adds preprocessor lines such as #include to the macro even if they
are not a part of the macro to begin with.

Fixes #58214.

Differential Revision: https://reviews.llvm.org/D135422
2022-10-10 19:57:58 -07:00
mydeveloperday 69e772768e [clang-format] Add support to remove unnecessary semicolons after function definition
Fixes: https://github.com/llvm/llvm-project/issues/58217

This change is to remove extraneous and unnecessary ';' from after a function definition, its off by default and carries the same "code modification" warning as some of our other code manipulating changes.

Reviewed By: HazardyKnusperkeks, owenpan

Differential Revision: https://reviews.llvm.org/D135466
2022-10-09 11:18:16 +01:00
Sam McCall 4b53c00173 [Format] Drop speculative test added in previous patch, it hits asserts? 2022-10-06 17:57:58 +02:00
Sam McCall 882a05afa1 [Format] Fix crash when hitting eof while lexing JS template string
Different loop termination conditions resulted in confusion of whether
*Offset was intended to be inside or outside the token.
This ultimately led to constructing an out-of-range SourceLocation.

Fix by making Offset consistently point *after* the token.

Differential Revision: https://reviews.llvm.org/D135356
2022-10-06 17:00:41 +02:00
owenca b60e7a7f1a [clang-format] Handle C# interpolated verbatim string prefix @$
Fixes #58062.

Differential Revision: https://reviews.llvm.org/D135026
2022-10-04 18:27:36 -07:00
Emilia Dreamer 1fa115b569
[clang-format] Correctly indent closing brace of compound requires
When a compound requirement is too long to fit onto a single line, the
braces are split apart onto separate lines, and the contained expression
is indented. However, this indentation would also apply to the closing
brace and the trailing return type requirement thereof.
This was because the indentation level was being restored after all
trailing things were already read

With this change, the initial level of the opening brace is set before
attempting to read any trailing return type requirements

Fixes https://github.com/llvm/llvm-project/issues/57108

Reviewed By: HazardyKnusperkeks, owenpan, MyDeveloperDay

Differential Revision: https://reviews.llvm.org/D134626
2022-10-01 08:16:57 +03:00
owenca 2d23175fae [clang-format] Fix a bug with C++ `export import <Foo/Bar>`
Fixes #57798.

Differential Revision: https://reviews.llvm.org/D134700
2022-09-28 19:10:12 -07:00
mitchell c0779756a0 [clang-format] Fix alignment in #else preprocessor blocks
Summary:
clang-format makes multiple passes when #if/#else preprocessor blocks are found.  It will make
one pass for normal code and code in the #if block, and then it will make another pass for just
the code in #else blocks. This often results in invalid alignment inside the else blocks because
they do not have any scope or indentAndNestingLevel context from their surrounding tokens/lines.

This patch remedies that by caching any initial indentAndNestingLevel from a second pass and
not breaking/returning early when a scope change is detected.

Fixes #36070

Reviewers: HazardyKnusperkeks, MyDeveloperDay

Tags: clang, clang-format

Differential Revision: https://reviews.llvm.org/D134042
2022-09-27 15:41:09 -04:00
Danil Sidoruk 258d7b86ee [clang-format] Handle constructor invocations after new operator in C# correct
Fixes #56549.

Differential Revision: https://reviews.llvm.org/D129926
2022-09-25 21:10:26 -07:00
Emilia Dreamer 39e6077d97
[clang-format] Look ahead before consuming `bool` in requires clause.
The comment handling the bool case says:
"bool is only allowed if it is directly followed by a paren for a cast"

This change more closely follows this directive by looking ahead for
the paren before consuming the bool keyword itself. Without a following
paren, the bool would be part of something else, such as a return type
for a function declaration

Fixes https://github.com/llvm/llvm-project/issues/57538

Reviewed By: HazardyKnusperkeks, owenpan, MyDeveloperDay

Differential Revision: https://reviews.llvm.org/D134325
2022-09-25 20:30:21 +03:00
Emilia Dreamer 7847225576
[clang-format] Correctly annotate static and consteval lambdas
`P1169` "static operator()" (https://wg21.link/P1169) is accepted to
C++23 and while clang itself doesn't exactly support it yet,
clang-format could quite easily.

This simply allows the keyword `static` to be a part of lambdas as
specified by the addition to [expr.prim.lambda.general]

While adding this, I noticed `consteval` lambdas also aren't handled,
so that keyword is now allowed to be a part of lambdas as well

Reviewed By: HazardyKnusperkeks, owenpan, MyDeveloperDay

Differential Revision: https://reviews.llvm.org/D134587
2022-09-25 20:29:55 +03:00
owenca e347c0fc9b [clang-format][NFC] Reformat the clang/unittests/Format directory
Also add a .clang-format file to clang/include/clang/Format and
clang/unittests/Format to keep the directories formatted.
2022-09-21 13:26:59 -07:00
owenca 6257832bf9 [clang-format] Wrap inserted braces only if preceded by comments
Fixes #57805.

Differential Revision: https://reviews.llvm.org/D134233
2022-09-20 12:09:39 -07:00
owenca 7349084e7a [clang-format] Update removed brace's next token's WhitespaceRange
Fixes #57803.

Differential Revision: https://reviews.llvm.org/D134146
2022-09-19 15:02:08 -07:00
mydeveloperday 95b3947111 [clang-format] JSON formatting add new option for controlling newlines in json arrays
Working in a mixed environment of both vscode/vim with a team configured prettier configuration, this can leave clang-format and prettier fighting each other over the formatting of arrays, both simple arrays of elements.

This review aims to add some "control knobs" to the Json formatting in clang-format to help align the two tools so they can be used interchangeably.

This will allow simply arrays `[1, 2, 3]` to remain on a single line but will break those arrays based on context within that array.

Happy to change the name of the option (this is the third name I tried)

Reviewed By: HazardyKnusperkeks, owenpan

Differential Revision: https://reviews.llvm.org/D133589
2022-09-19 17:54:39 +01:00
Emilia Dreamer 8dab452740
[clang-format] Disallow requires clauses to become function declarations
There already exists logic to disallow requires *expressions* to be
treated as function declarations, but this expands it to include
requires *clauses*, when they happen to also be parenthesized.

Previously, in the following case:

```
template <typename T>
  requires(Foo<T>)
T foo();
```

The line with the requires clause was actually being considered as the
line with the function declaration due to the parentheses, and the
*real* function declaration on the next line became a trailing
annotation

(Together with https://reviews.llvm.org/D134049) Fixes https://github.com/llvm/llvm-project/issues/56213

Reviewed By: HazardyKnusperkeks, owenpan

Differential Revision: https://reviews.llvm.org/D134052
2022-09-19 04:04:31 +03:00
Emilia Dreamer 0bf63f0d1b
[clang-format] Disallow trailing return arrows to be operators
In the following construction:
`template <typename T> requires Foo<T> || Bar<T> auto func() -> int;`

The `->` of the trailing return type was actually considered as an
operator as part of the binary operation in the requires clause, with
the precedence level of `PrecedenceArrowAndPeriod`, leading to fake
parens being inserted in strange locations, that would never be closed.

Fixes one part of https://github.com/llvm/llvm-project/issues/56213
(the rest will probably be in a separate patch)

Reviewed By: HazardyKnusperkeks, owenpan

Differential Revision: https://reviews.llvm.org/D134049
2022-09-19 04:04:31 +03:00
sstwcw e5964223d9 [clang-format] Fix template arguments in macros
Fixes https://github.com/llvm/llvm-project/issues/57738

old
```
#define FOO(typeName, realClass)                               \
  {                                                            \
#typeName, foo < FooType>(new foo <realClass>(#typeName))  \
  }
```
new
```
#define FOO(typeName, realClass)                                \
  { #typeName, foo<FooType>(new foo<realClass>(#typeName)) }
```

Previously, when an UnwrappedLine began with a hash in a macro
definition, the program incorrectly assumed the line was a preprocessor
directive.  It should be stringification.

The rule in spaceRequiredBefore was added in 8b5297117b.  Its purpose is
to add a space in an include directive.  It also added a space to a
template opener when the line began with a stringification hash.  So we
changed it.

Reviewed By: HazardyKnusperkeks, owenpan

Differential Revision: https://reviews.llvm.org/D133954
2022-09-16 13:30:46 +00:00
sstwcw 2183fe2160 [clang-format] Parse the else part of `#if 0`
Fixes https://github.com/llvm/llvm-project/issues/57539

Previously things outside of `#if` blocks were parsed as if only the
first branch of the conditional compilation branch existed, unless the
first condition is 0.  In that case the outer parts would be parsed as
if nothing inside the conditional parts existed.  Now we use the second
conditional branch if the first condition is 0.

Reviewed By: owenpan

Differential Revision: https://reviews.llvm.org/D133647
2022-09-16 13:30:46 +00:00
owenca 5889ed83a0 [clang-format] Don't insert braces for loops with a null statement
This is a workaround for #57539.

Fixes #57509.

Differential Revision: https://reviews.llvm.org/D133635
2022-09-12 00:37:47 -07:00
Emilia Dreamer 247613548b [clang-format] Change heuristic for locating lambda template arguments
Previously, the heuristic was simply to look for template argument-
specific keywords, such as typename, class, template and auto
that are preceded by a left angle bracket <.

This changes the heuristic to instead look for a left angle bracket <
preceded by a right square bracket ], since according to the C++
grammar, the template arguments must *directly* follow the introducer.
(This sort of check might just end up being *too* aggressive)

This patch also adds a bunch more token annotator tests for lambdas,
specifically for some of the stranger forms of lambdas now allowed as
of C++20 or soon-to-be-allowed as part of C++23.

Fixes https://github.com/llvm/llvm-project/issues/57093

This does NOT resolve the FIXME regarding explicit template lists, but
perhaps it gets closer

Differential Revision: https://reviews.llvm.org/D132295
2022-09-06 12:24:19 +02:00
Emilia Dreamer bd3dd10a8b [clang-format] Concepts: allow identifiers after negation
Previously, the formatter would refuse to treat identifiers within a
compound concept definition as actually part of the definition, if
they were after the negation operator !. It is now made consistent
with the likes of && and ||.

Fixes https://github.com/llvm/llvm-project/issues/55898

Differential Revision: https://reviews.llvm.org/D131978
2022-09-05 12:35:40 +02:00
Emilia Dreamer c6e7752f8e [clang-format] Allow `throw` to be a keyword in front of casts
This makes throw more similar to return. However, unlike return,
it has to more strict as to not remove spaces after usages of throw as
a (deprecated) exception specifier.

Fixes https://github.com/llvm/llvm-project/issues/57391

Differential Revision: https://reviews.llvm.org/D132762
2022-09-05 12:35:39 +02:00