Commit Graph

997 Commits

Author SHA1 Message Date
Konrad Kleine d46fa023ca [clang-format] SortIncludes should support "@import" lines in Objective-C
Fixes [[ https://github.com/llvm/llvm-project/issues/38995 | #38995 ]]

This is an attempt to modify the regular expression to identify
`@import` and `import` alongside the regular `#include`. The challenging
part was not to support `@` in addition to `#` but how to handle
everything that comes after the `include|import` keywords. Previously
everything that wasn't `"` or `<` was consumed. But as you can see in
this example from the issue #38995, there is no `"` or `<` following the
keyword:

```
@import Foundation;
```

I experimented with a lot of fancy and useful expressions in [this
online regex tool](https://regex101.com) only to find out that some
things are simply not supported by the regex implementation in LLVM.

 * For example the beginning `[\t\ ]*` should be replacable by the
   horizontal whitespace character `\h*` but this will break the
   `SortIncludesTest.LeadingWhitespace` test.

That's why I've chosen to come back to the basic building blocks.

The essential change in this patch is the change from this regular
expression:

```
^[\t\ ]*#[\t\ ]*(import|include)[^"<]*(["<][^">]*[">])
        ~                              ~~~~~~~~~~~~~~
        ^                              ^
        |                              |
        only support # prefix not @    |
                                       only support "" and <> as
delimiters
                                       no support for C++ modules and ;
                                       ending. Also this allows for ">
                                       or <" or "" or <> which all seems
                                       either off or wrong.
```

to this:

```
^[\t\ ]*[@#][\t\ ]*(import|include)([^"]*("[^"]+")|[^<]*(<[^>]+>)|[\t\
]*([^;]+;))
        ~~~~                        ~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~
~~~~~~~~~~~~~~
        ^                                 ^           ^       ^       ^
        |                                 |           |       |       |
        Now support @ and #.            Clearly support "" and <> as
well as an
                                        include name without enclosing
characters.
                                        Allows for no mixture of "> or
<" or
                                        empty include names.

```

Here is how I've tested this patch:

```
ninja clang-Format
ninja FormatTests
./tools/clang/unittests/Format/FormatTests
--gtest_filter=SortIncludesTest*
```

And if that worked I doubled checked that nothing else broke by running
all format checks:

```
./tools/clang/unittests/Format/FormatTests
```

One side effect of this change is it should partially support
[C++20 Module](https://en.cppreference.com/w/cpp/language/modules)
`import` lines without the optional `export` in front. Adding
this can be a change on its own that shouldn't be too hard. I say
partially because the `@` or `#` are currently *NOT* optional in the
regular expression.

I see an opportunity to optimized the matching to exclude `@include` for
example. But eventually these should be caught by the compiler, so...

With my change, the matching group is not at a fixed position any
longer. I decided to
choose the last match (group) that is not empty.

Reviewed By: HazardyKnusperkeks

Differential Revision: https://reviews.llvm.org/D121370
2022-04-20 07:03:35 +00:00
owenca 0cb9c6ea83 [clang-format] Allow empty .clang-format file
Differential Revision: https://reviews.llvm.org/D123535
2022-04-12 21:20:54 -07:00
owenca 0cde8bdb0b Revert "[clang-format] Allow empty .clang-format file"
This reverts commit 4e814a6f2d.
2022-04-12 16:05:39 -07:00
owenca 4e814a6f2d [clang-format] Allow empty .clang-format file
Differential Revision: https://reviews.llvm.org/D123535
2022-04-12 15:45:22 -07:00
owenca c80eaa919f Revert "[clang-format] Allow empty .clang-format file"
This reverts commit 6eafda0ef0.
2022-04-12 14:28:02 -07:00
owenca 6eafda0ef0 [clang-format] Allow empty .clang-format file
Differential Revision: https://reviews.llvm.org/D123535
2022-04-12 13:54:12 -07:00
sstwcw c24b3db45c [clang-format] Add option to align compound assignments like `+=`
Reviewed By: curdeius, HazardyKnusperkeks, MyDeveloperDay

Differential Revision: https://reviews.llvm.org/D119599
2022-03-14 04:41:40 +00:00
owenca 9f616a467f [clang-format][NFC] Group QualifierAlignment with other C++ passes
Also increases the initial size of Passes to 8 and move the
definition of BracesInserter up.

Differential Revision: https://reviews.llvm.org/D121434
2022-03-11 14:18:00 -08:00
owenca 0be56c8701 [clang-format][NFC] Group all C++ passes under isCpp()
Also removes a not very helpful comment.
2022-03-10 14:30:30 -08:00
owenca e2b219bded [clang-format] Handle "// clang-format off" for RemoveBracesLLVM
Differential Revision: https://reviews.llvm.org/D121352
2022-03-10 13:30:53 -08:00
Nico Weber e6a8b92b89 [clang-format] Fix namespace end comments in ObjC++ files too
See also d96ae86735.

Differential Revision: https://reviews.llvm.org/D121112
2022-03-07 13:30:25 -05:00
owenca 1aa608a020 [clang-format] Handle wrapped else for RemoveBracesLLVM
Removes the newline before the right brace that's followed by an
else on the next line.

Differential Revision: https://reviews.llvm.org/D120873
2022-03-03 04:53:15 -08:00
owenca c05da55bdf [clang-format] Handle trailing comment for InsertBraces
Differential Revision: https://reviews.llvm.org/D120503
2022-02-25 12:29:47 -08:00
owenca 77e60bc42c [clang-format] Add option to insert braces after control statements
Adds a new option InsertBraces to insert the optional braces after
if, else, for, while, and do in C++.

Differential Revision: https://reviews.llvm.org/D120217
2022-02-21 20:16:25 -08:00
Krystian Kuzniarek aacc110bdc [clang-format][NFC] Fix typos and inconsistencies
Differential Revision: https://reviews.llvm.org/D120220
2022-02-20 17:20:34 -08:00
Björn Schäpers b786a4aefe [clang-format] Extend SpaceBeforeParens for requires
We can now configure the space between requires and the following paren,
seperate for clauses and expressions.

Differential Revision: https://reviews.llvm.org/D113369
2022-02-15 21:37:36 +01:00
Björn Schäpers 9aab0db13f [clang-format] Improve require and concept handling
- Added an option where to put the requires clauses.
- Renamed IndentRequires to IndentRequiresClause.
- Changed BreakBeforeConceptDeclaration from bool to an enum.

Fixes https://llvm.org/PR32165, and https://llvm.org/PR52401.

Differential Revision: https://reviews.llvm.org/D113319
2022-02-11 22:42:37 +01:00
Sam McCall acc3ce945c [Format] Don't derive pointers right based on space before method ref-qualifiers
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
2022-02-04 12:13:58 +01:00
Sven van Haastregt 9694332b81 [clang-format] Add missing newline in -style help 2022-02-03 12:12:29 +00:00
Marek Kurdej d079995dd0 [clang-format] Elide unnecessary braces. NFC. 2022-02-02 15:28:53 +01:00
Marek Kurdej 630c736047 [clang-format] Elide unnecessary braces. NFC. 2022-02-02 14:36:01 +01:00
Marek Kurdej 61f09bcf11 [clang-format] Use llvm::seq instead of std::iota. NFC. 2022-02-02 14:00:50 +01:00
Marek Kurdej bc40b76b5b [clang-format] Correctly parse C99 digraphs: "<:", ":>", "<%", "%>", "%:", "%:%:".
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
2022-02-02 10:25:24 +01:00
Marek Kurdej af8f1dbb43 [clang-format] Use std::iota and reserve when sorting Java imports. NFC.
This way we have at most 1 allocation even if the number of includes is greater than the on-stack size of the small vector.
2022-02-01 14:29:31 +01:00
Marek Kurdej e75a3428a9 [clang-format] Use std::iota and reserve. NFC.
This way we have at most 1 allocation even if the number of includes is greater than the on-stack size of the small vector.
2022-02-01 14:24:01 +01:00
Marek Kurdej 545317cb8e [clang-format] Use ranged for loops. NFC. 2022-02-01 14:10:48 +01:00
Marek Kurdej 95bf0a9ebd [clang-format] Don't break block comments when sorting includes.
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
2022-02-01 08:51:10 +01:00
Marek Kurdej 82452be5cb [clang-format] Refactor: add FormatToken::hasWhitespaceBefore(). NFC.
This factors out a pattern that comes up from time to time.

Reviewed By: MyDeveloperDay, HazardyKnusperkeks, owenpan

Differential Revision: https://reviews.llvm.org/D117769
2022-01-20 21:16:17 +01:00
Cameron Mulhern 966f24e5a6 [clang-format] Add a BlockIndent option to AlignAfterOpenBracket
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
2022-01-17 09:03:23 +01:00
Owen Pan 533fbae8d8 [clang-format] Add experimental option to remove LLVM braces
See the style examples at:
https://llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single-statement-bodies-of-if-else-loop-statements

Differential Revision: https://reviews.llvm.org/D116316
2022-01-14 15:10:17 -08:00
Marek Kurdej 359b4e6cdb [clang-format] Use prefix increment and decrement. NFC. 2022-01-07 11:19:53 +01:00
Marek Kurdej 46db030188 [clang-format] Simplify raw string regex. NFC.
Introduced in https://reviews.llvm.org/D115168.

Reviewed By: MyDeveloperDay, HazardyKnusperkeks

Differential Revision: https://reviews.llvm.org/D116647
2022-01-05 13:39:28 +01:00
Rajat Bajpai da6b0d0b76 [clang-format] Add an option to add a space between operator overloading and opening parentheses
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
2022-01-04 17:23:23 +01:00
ksyx 6f6f88ffda [clang-format] Style to separate definition blocks
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
2022-01-03 15:47:39 -05:00
G. Pery cfe3180742 [clang-format] Add penalty for breaking after '('
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
2022-01-03 21:06:34 +01:00
Zhao Wei Liew b9e173fcd4 [clang-format] Add option to explicitly specify a config file
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
2022-01-03 11:43:25 +01:00
Zhao Wei Liew 0090cd4e7a [clang-format] Support inheriting from more than 1 parents in the fallback case
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
2022-01-03 11:36:00 +01:00
mydeveloperday 142e79b868 [clang-format] NFC use recently added Style.isJavaScript()
Improve the readability of these if(Style==FormatStyle::LK_JavsScript) clauses
2021-12-21 14:24:12 +00:00
mydeveloperday 05bea533d1 [clang-format] [PR49298] Sort includes pass will sort inside raw strings
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/D115168

Fixes #48642
2021-12-12 17:00:43 +00:00
mydeveloperday 93fc91610f [clang-format] NFC - recent changes caused clang-format to no longer be clang-formatted.
The following 2 commits caused files in clang-format to no longer be clang-formatted.

we would lose our "clean" status https://releases.llvm.org/13.0.0/tools/clang/docs/ClangFormattedStatus.html

c2271926a4  - Make clang-format fuzz through Lexing with asserts enabled (https://github.com/llvm/llvm-project/commit/c2271926a4fc )

84bf5e3286 - Fix various problems found by fuzzing. (https://github.com/llvm/llvm-project/commit/84bf5e328664)

Reviewed By: HazardyKnusperkeks, owenpan

Differential Revision: https://reviews.llvm.org/D114430
2021-11-24 09:45:32 +00:00
Zarko Todorovski d8e5a0c42b [clang][NFC] Inclusive terms: replace some uses of sanity in clang
Rewording of comments to avoid using `sanity test, sanity check`.

Reviewed By: aaron.ballman, Quuxplusone

Differential Revision: https://reviews.llvm.org/D114025
2021-11-19 14:58:35 -05:00
Manuel Klimek c2271926a4 Make clang-format fuzz through Lexing with asserts enabled.
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.
2021-11-19 14:44:06 +01:00
C. Rayroud 6facafe7da [clang-format] Refactor SpaceBeforeParens to add options
The coding style of some projects requires to have more control on space
before opening parentheses.
The goal is to add the support of clang-format to more projects.
For example adding a space only for function definitions or
declarations.
This revision adds SpaceBeforeParensOptions to configure each option
independently from one another.

Differentiel Revision: https://reviews.llvm.org/D110833
2021-11-09 21:51:45 +01:00
Quinn Pham c71fbdd87b [NFC] Inclusive language: Remove instances of master in URLs
[NFC] This patch fixes URLs containing "master". Old URLs were either broken or
redirecting to the new URL.

Reviewed By: #libc, ldionne, mehdi_amini

Differential Revision: https://reviews.llvm.org/D113186
2021-11-05 08:48:41 -05:00
mydeveloperday a44ab17025 [clang-format] Add Left/Right Const fixer capability
Developers these days seem to argue over east vs west const like they used to argue over tabs vs whitespace or the various bracing style. These previous arguments were mainly eliminated with tools like `clang-format` that allowed those rules to become part of your style guide. Anyone who has been using clang-format in a large team over the last couple of years knows that we don't have those religious arguments any more, and code reviews are more productive.

https://www.youtube.com/watch?v=fv--IKZFVO8
https://mariusbancila.ro/blog/2018/11/23/join-the-east-const-revolution/
https://www.youtube.com/watch?v=z6s6bacI424

The purpose of this revision is to try to do the same for the East/West const discussion. Move the debate into the style guide and leave it there!

In addition to the new `ConstStyle: Right` or `ConstStyle: Left` there is an additional command-line argument `--const-style=left/right` which would allow an individual developer to switch the source back and forth to their own style for editing, and back to the committed style before commit. (you could imagine an IDE might offer such a switch)

The revision works by implementing a separate pass of the Annotated lines much like the SortIncludes and then create replacements for constant type declarations.

Differential Revision: https://reviews.llvm.org/D69764
2021-09-23 20:00:33 +01:00
Nico Weber f119170579 [clang] Fix a few comment typos to cycle bots 2021-09-20 18:48:34 -04:00
owenca 4b1fde8a2b [clang-format] Add PackConstructorInitializers backward compat test
Add backward compatibility tests for mapping the deprecated
ConstructorInitializerAllOnOneLineOrOnePerLine and
AllowAllConstructorInitializersOnNextLine to
PackConstructorInitializers.

Differential Revision: https://reviews.llvm.org/D108882
2021-08-29 13:47:11 -07:00
owenca 170a3c6f7a [clang-format] Fix AllowAllConstructorInitializersOnNextLine value
The default value of the now deprecated
AllowAllConstructorInitializersOnNextLine was always true
regardless of the value of BasedOnStyle. This patch fixes the typo
in the code that handles the related backward compatibility.
2021-08-27 14:47:49 -07:00
owenca 8a780a2f18 [clang-format] Group options that pack constructor initializers
Add a new option PackConstructorInitializers and deprecate the
related options ConstructorInitializerAllOnOneLineOrOnePerLine and
AllowAllConstructorInitializersOnNextLine. Below is the mapping:

PackConstructorInitializers  ConstructorInitializer... AllowAll...
        Never                            -                  -
        BinPack                        false                -
        CurrentLine                    true               false
        NextLine                       true               true

The option value Never fixes PR50549 by always placing each
constructor initializer on its own line.

Differential Revision: https://reviews.llvm.org/D108752
2021-08-27 06:27:46 -07:00
mydeveloperday 8b7881a084 [clang-format] Add basic support for formatting JSON
I find as I develop I'm moving between many different languages C++,C#,JavaScript all the time. As I move between the file types I like to keep `clang-format` as my formatting tool of choice. (hence why I initially added C# support  in {D58404}) I know those other languages have their own tools but I have to learn them all, and I have to work out how to configure them, and they may or may not have integration into my IDE or my source code integration.

I am increasingly finding that I'm editing additional JSON files as part of my daily work and my editor and git commit hooks are just not setup to go and run [[ https://stedolan.github.io/jq/ | jq ]], So I tend to go to  [[ https://jsonformatter.curiousconcept.com/ | JSON Formatter ]] and copy and paste back and forth. To get nicely formatted JSON. This is a painful process and I'd like a new one that causes me much less friction.

This has come up from time to time:

{D10543}
https://stackoverflow.com/questions/35856565/clang-format-a-json-file
https://bugs.llvm.org/show_bug.cgi?id=18699

I would like to stop having to do that and have formatting JSON as a first class clang-format support `Language` (even if it has minimal style settings at present).

This revision adds support for formatting JSON using the inbuilt JSON serialization library of LLVM, With limited control at present only over the indentation level

This adds an additional Language into the .clang-format file to separate the settings from your other supported languages.

Reviewed By: HazardyKnusperkeks

Differential Revision: https://reviews.llvm.org/D93528
2021-06-26 15:20:17 +01:00