179 Commits

Author SHA1 Message Date
Owen Pan
91c4db0061 [clang-format][NFC] Replace !is() with isNot()
Differential Revision: https://reviews.llvm.org/D158571
2023-08-24 01:27:24 -07:00
Sedenion
0570cc568f [clang-format] Fix indent for selective formatting
The problem was that the LevelIndentTracker remembered
the indentation level of previous deeper levels when
leaving a scope. Afterwards, when it entered again a
deeper level, it blindly reused the previous
indentation level. In case the --lines option was used
such that the previous deeper level was not formatted,
that previous level was whatever happened to be there
in the source code. The formatter simply believed it.

This is fixed by letting the LevelIndentTracker forget
the previous deeper levels when stepping out of them
(=> change in LevelIndentTracker::nextLine()).
Note that this used to be the case until LLVM 14.0.6,
but was changed in https://reviews.llvm.org/D129064
(#56352) to fix a crash. Our commit here essentially
reverts that crash fix. It was incorrect/incomplete.

Fixes #58464.
Fixes #59178.
Fixes #62799.

Differential Revision: https://reviews.llvm.org/D151047
2023-07-18 14:10:53 -07:00
Sedenion
e4aa1428a2 [clang-format] Refactoring and asserts in LevelIndentTracker. (NFC)
adjustToUnmodifiedLine: The code does something only for non-PP-directives.
This is now reflected by putting the if-check to the top. This also ensures
that the assert() there is executed only if IndentForLevel is actually
accessed.

getIndent(): assert valid index into IndentForLevel.

Added explanation regarding the intention of IndentForLevel.

Differential Revision: https://reviews.llvm.org/D155094
2023-07-18 13:32:07 -07:00
Owen Pan
875b881186 [clang-format][NFC] Remove redundant parentheses in the source code
Reformat the source code with RemoveParentheses set to ReturnStatement.
2023-07-11 17:05:00 -07:00
Owen Pan
8e85739a5f [clang-format] Don't finalize #if, #else, #endif, etc.
Don't finalize a preprocessor branch directive if it's the first
token of an annotated line. See the rationale at
https://reviews.llvm.org/D150057#inline-1449546.

Fixes #63379

Differential Revision: https://reviews.llvm.org/D153243
2023-06-21 15:15:57 -07:00
Owen Pan
441108ccba Reland [clang-format] Fix overlapping whitespace replacements before PPDirective
If the first token of an annotated line already has a computed Newlines,
reuse it to avoid potential overlapping whitespace replacements before
preprocessor branching directives.

Fixes #62892.

Differential Revision: https://reviews.llvm.org/D151954
2023-06-16 17:00:12 -07:00
Owen Pan
829ed96b77 Reland [clang-format] Add the KeepEmptyLinesAtEOF option 2023-06-13 10:02:10 -07:00
Paul Kirth
b6a718016c [clang-format] Add test case for issue 63170
After https://reviews.llvm.org/D151954 we've noticed some issues w/
clang-format behavior, as outlined in
https://github.com/llvm/llvm-project/issues/63170.

Valid C/C++ files, that were previously accepted, are now rejected by
clang-format, emitting the message:

"The new replacement overlaps with an existing replacement."

This reverts commit 4b9764959dc4b8783e18747c1742ab164e4bc4ee and
d2627cf88d2553a4c2e850430bdb908a4b7d2e52, which depends on it.

Reviewed By: phosek

Differential Revision: https://reviews.llvm.org/D152473
2023-06-09 20:10:19 +00:00
Leonard Chan
9f00eb9975 Revert "Revert "[clang-format] Fix overlapping replacements before PPDirectives""
This reverts commit 94e75469597f197f9c4b45baa6c8a576c78dbd02.

Apparently I broke some builders with the original revert: http://45.33.8.238/linux/109159/step_7.txt
2023-06-08 00:15:30 +00:00
Leonard Chan
94e7546959 Revert "[clang-format] Fix overlapping replacements before PPDirectives"
This reverts commit 4b9764959dc4b8783e18747c1742ab164e4bc4ee.

Reverting since this causes clang-formtat to incorrectly fall into an
error path yet return a zero exit code despite not formatting the file
at all.

See https://github.com/llvm/llvm-project/issues/63170
2023-06-07 23:44:32 +00:00
Owen Pan
d2627cf88d [clang-format] Add the KeepEmptyLinesAtEOF option
Adds an option KeepEmptyLinesAtEOF to keep empty lines (up to
MaxEmptyLinesToKeep) before EOF. This remedies the probably unintentional
change in behavior introduced in 3d3ea84a4f8f, which started to always
remove empty lines before EOF.

Fixes #56054.
Fixes #63150.

Differential Revision: https://reviews.llvm.org/D152305
2023-06-07 14:17:58 -07:00
Owen Pan
4b9764959d [clang-format] Fix overlapping replacements before PPDirectives
If the first token of an annotated line is finalized, reuse its
NewlinesBefore value to avoid potential overlapping whitespace
replacements before preprocessor branching directives.

Fixes #62892.

Differential Revision: https://reviews.llvm.org/D151954
2023-06-03 12:33:03 -07:00
Owen Pan
8e16365cb6 Revert "[clang-format] Fix indentation for selective formatting"
This reverts commit 72ab89e3197cc1bee3b9774edb504690e3e43ed0.

Reverted due to bots failures e.g.
https://lab.llvm.org/buildbot/#/builders/139/builds/41339.
2023-05-23 22:18:13 -07:00
Sedenion
72ab89e319 [clang-format] Fix indentation for selective formatting
The problem was that the LevelIndentTracker remembered
the indentation level of previous deeper levels when
leaving a scope. Afterwards, when it entered again a
deeper level, it blindly reused the the previous
indentation level. In case of the --lines option
configured such that the previous deeper level was not
formatted, that previous level was whatever happened
to be there in the source code. The formatter simply
believed it.

This is fixed by letting the LevelIndentTracker forget
the previous deeper levels when stepping out of them
(=> change in LevelIndentTracker::nextLine()).
Note that this used to be the case until LLVM 14.0.6,
but was changed in
https://github.com/llvm/llvm-project/issues/56352 to
fix a crash. Our commit here essentially reverts that
crash fix. It seemed to have been incorrect. The proper
fix is to set the AnnotedLine::Level of joined lines
correctly (=> change in LineJoiner::join()).

See
https://github.com/llvm/llvm-project/issues/59178#issuecomment-1542637781
for some more details.

Fixes #58464.
Fixes #59178.

Differential Revision: https://reviews.llvm.org/D151047
2023-05-23 19:40:24 -07:00
Emilia Kond
06763ea5d8
[clang-format] Ignore first token when finding MustBreak
When in ColumnLimit 0, the formatter looks for MustBreakBefore in the
line in order to check if a line is allowed to be merged onto one line.

However, since MustBreakBefore is really a property of the gap between
the token and the one previously, I belive the check is erroneous in
checking all the tokens in a line, since whether the previous line ended
with a forced line break should have no effect on whether the current
line is allowed to merge with the next one.

This patch changes the check to skip the first token in
`LineJoiner.containsMustBreak`.

This patch also changes a test, which is not ideal, but I believe the
test also suffered from this bug. The test case in question sets
AllowShortFunctionsOnASingleLine to "Empty", but the empty function in
said test case isn't merged to a single line, because of the very same
bug this patch fixes.

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

Reviewed By: HazardyKnusperkeks, owenpan, MyDeveloperDay

Differential Revision: https://reviews.llvm.org/D150614
2023-05-18 05:50:26 +03:00
Manuel Klimek
9e9e096ae9 [clang-format] Fix dropped 'else'.
'else' was dropped accidentally in 398cddf6acec.

Patch by Jared Grubb.

Differential revision: https://reviews.llvm.org/D146310
2023-04-21 11:59:45 +00:00
Jon Phillips
5c614bd88f [clang-format] Fix bugs with "LambdaBodyIndentation: OuterScope"
The previous implementation of the option corrupted the parenthesis
state stack. (See https://reviews.llvm.org/D102706.)

Fixes #55708.
Fixes #53212.
Fixes #52846.
Fixes #59954.

Differential Revision: https://reviews.llvm.org/D146042
2023-04-05 14:38:38 -07:00
mydeveloperday
0ca6dd96d6 [clang-format] NFC ensure clang-format is itself clang-formatted
Some patch in the past introduce this non clang-formatted change
2023-03-29 20:01:03 +01:00
Manuel Klimek
398cddf6ac [clang-format] Fix assertion that doesn't hold under fuzzing. 2023-02-27 10:50:42 +00:00
Emilia Dreamer
7ba91016c6
[clang-format] Rewrite how indent is reduced for compacted namespaces
The previous version set the indentation directly using IndentForLevel,
however, this has a few caveats, namely:

* IndentForLevel applies to all scopes of the entire program being
  formatted, but this indentation should only be adjusted for scopes
  of namespaces.

* The method it used only set the correct indent amount if one wasn't
  already set for a given level, meaning it didn't work correctly if
  anything with indentation preceded a namespace keyword. This
  includes preprocessing directives if using IndentPPDirectives.

This patch instead reduces the Level of all lines within namespaces
which are compacted by CompactNamespaces. This means they will get
correct indentation using the normal process.

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

Reviewed By: owenpan, MyDeveloperDay, HazardyKnusperkeks

Differential Revision: https://reviews.llvm.org/D144296
2023-02-25 12:13:53 +02:00
Manuel Klimek
01402831aa [clang-format] Add simple macro replacements in formatting.
Add configuration to specify macros.
Macros will be expanded, and the code will be parsed and annotated
in the expanded state. In a second step, the formatting decisions
in the annotated expanded code will be reconstructed onto the
original unexpanded macro call.

Eventually, this will allow to remove special-case code for
various macro options we accumulated over the years in favor of
one principled mechanism.

Differential Revision: https://reviews.llvm.org/D144170
2023-02-24 15:44:24 +00:00
Owen Pan
0ef289e5b2 [clang-format][NFC] Clean up nullptr comparison style
For example, use 'Next' instead of 'Next != nullptr',
and '!Next' instead of 'Next == nullptr'.

Differential Revision: https://reviews.llvm.org/D144355
2023-02-21 02:56:27 -08: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
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
owenca
92d8738c38 [clang-format] Fix a bug in merging blocks with a wrapped l_brace
When the opening brace of a control statement block is wrapped, we
must check the previous line to determine whether to try to merge
the block.

Fixes #38639.
Fixes #48007.
Fixes #57421.

Differential Revision: https://reviews.llvm.org/D133093
2022-09-02 21:38:36 -07:00
Sheng
f4feb7dd6a [NFC] Fix typo 2022-08-28 15:16:34 +08:00
owenca
41214456de [clang-format] Fix BeforeHash indent of comments above PPDirective
Fixes #56326.

Differential Revision: https://reviews.llvm.org/D132097
2022-08-21 18:23:14 -07:00
sstwcw
6db0c18b1a [clang-format] Handle Verilog modules
Now things inside hierarchies like modules and interfaces are
indented.  When the module header spans multiple lines, all except the
first line are indented as continuations.  We added the property
`IsContinuation` to mark lines that should be indented this way.

In order that the colons inside square brackets don't get labeled as
`TT_ObjCMethodExpr`, we added a check to only use this type when the
language is not Verilog.

Differential Revision: https://reviews.llvm.org/D128712
2022-07-29 00:38:30 +00:00
owenca
36229fa388 [clang-format][NFC] Replace most of std::vector with SmallVector
Differential Revision: https://reviews.llvm.org/D129466
2022-07-13 16:45:22 -07:00
owenca
c84d29acbf [clang-format][NFC] Clean up IndentForLevel in LevelIndentTracker
Differential Revision: https://reviews.llvm.org/D129105
2022-07-07 15:33:09 -07:00
Marek Kurdej
14c30c70c4 [clang-format] Avoid crash in LevelIndentTracker.
Fixes https://github.com/llvm/llvm-project/issues/56352.

Reviewed By: HazardyKnusperkeks, owenpan, MyDeveloperDay

Differential Revision: https://reviews.llvm.org/D129064
2022-07-07 10:15:45 +02:00
owenca
664ce34e81 [clang-format] Quit analyzing solution space for large state count
Fixes #56043.

Differential Revision: https://reviews.llvm.org/D128574
2022-06-26 13:15:07 -07:00
owenca
bebf7bdf9a [clang-format][NFC] Insert/remove braces in clang/lib/Format/
Differential Revision: https://reviews.llvm.org/D126157
2022-05-24 19:06:04 -07:00
owenca
f4d52cad67 [clang-format] Fix a bug in "AfterControlStatement: MultiLine"
Fixes #55582.

Differential Revision: https://reviews.llvm.org/D125959
2022-05-21 15:10:21 -07:00
owenca
221c2b68dd [clang-format] Fix a crash on AllowShortFunctionsOnASingleLine
Fixes #55008.

Differential Revision: https://reviews.llvm.org/D124152
2022-04-21 14:56:30 -07:00
Arthur Eubanks
19884d62c4 [clang-format] Don't skip PP lines if original line was a PP line when trying to merge lines
Fixes a crash introduced in D123737 where LastNonComment would be null.

Reviewed By: curdeius

Differential Revision: https://reviews.llvm.org/D124036
2022-04-20 08:42:30 -07:00
Arthur Eubanks
f14ebe91c5 [clang-format] Skip preprocessor lines when finding the record lbrace
With D117142, we would now format

```
struct A {
#define A
  void f() { a(); }
#endif
};
```

into

```
struct A {
#ifdef A
  void f() {
    a();
  }
#endif
};
```

because we were looking for the record lbrace without skipping preprocess lines.

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

Reviewed By: curdeius, owenpan

Differential Revision: https://reviews.llvm.org/D123737
2022-04-14 09:31:15 -07:00
sstwcw
f6740fe483 [clang-format] Indent import statements in JavaScript.
[clang-format] Indent import statements in JavaScript.

Take for example this piece of code found at
<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import>.

```
for (const link of document.querySelectorAll("nav > a")) {
  link.addEventListener("click", e => {
    e.preventDefault();

    import('/modules/my-module.js')
        .then(module => {
          module.loadPageInto(main);
        })
        .catch(err => {
          main.textContent = err.message;
        });
  });
}
```

Previously the import line would be unindented, looking like this.

```
for (const link of document.querySelectorAll("nav > a")) {
  link.addEventListener("click", e => {
    e.preventDefault();

import('/modules/my-module.js')
        .then(module => {
          module.loadPageInto(main);
        })
        .catch(err => {
          main.textContent = err.message;
        });
  });
}
```

Actually we were going to fix this along with fixing Verilog import
statements.  But the patch got too big.

Reviewed By: MyDeveloperDay, curdeius

Differential Revision: https://reviews.llvm.org/D121906
2022-03-30 23:17:27 +00:00
Marek Kurdej
0570af1758 [clang-format] Fix incorrect assertion on macro definitions with keyword class.
Fixes https://github.com/llvm/llvm-project/issues/54348.
2022-03-13 22:17:48 +01:00
Marek Kurdej
d03e342803 [clang-format] Fix assertion failure/crash with AllowShortFunctionsOnASingleLine: Inline/InlineOnly.
Fixes https://github.com/llvm/llvm-project/issues/54147.

When handling `AllowShortFunctionsOnASingleLine`, we were searching for the last line with a smaller level than the current line. The search was incorrect when the first line had the same level as the current one. This led to an unsatisfied assumption about the existence of a brace (non-comment token).

Reviewed By: HazardyKnusperkeks, owenpan

Differential Revision: https://reviews.llvm.org/D120902
2022-03-07 16:54:08 +01:00
Marek Kurdej
ef39235cb9 [clang-format] Make checking for a record more robust and avoid a loop. 2022-02-16 23:05:49 +01:00
Marek Kurdej
d81f003ce1 [clang-format] Fix formatting of struct-like records followed by variable declaration.
Fixes https://github.com/llvm/llvm-project/issues/24781.
Fixes https://github.com/llvm/llvm-project/issues/38160.

This patch splits `TT_RecordLBrace` for classes/enums/structs/unions (and other records, e.g. interfaces) and uses the brace type to avoid the error-prone scanning for record token.

The mentioned bugs were provoked by the scanning being too limited (and so not considering `const` or `constexpr`, or other qualifiers, on an anonymous struct variable declaration).

Moreover, the proposed solution is more efficient as we parse tokens once only (scanning being parsing too).

Reviewed By: MyDeveloperDay, HazardyKnusperkeks

Differential Revision: https://reviews.llvm.org/D119785
2022-02-16 22:37:32 +01:00
Marek Kurdej
9cb9445979 [clang-format] Correctly format loops and if statements even if preceded with comments.
Fixes https://github.com/llvm/llvm-project/issues/53758.

Braces in loops and in `if` statements with leading (block) comments were formatted according to `BraceWrapping.AfterFunction` and not `AllowShortBlocksOnASingleLine`/`AllowShortLoopsOnASingleLine`/`AllowShortIfStatementsOnASingleLine`.

Previously, the code:
```
while (true) {
  f();
}
/*comment*/ while (true) {
  f();
}
```

was incorrectly formatted to:
```
while (true) {
  f();
}
/*comment*/ while (true) { f(); }
```

when using config:
```
BasedOnStyle: LLVM
BreakBeforeBraces: Custom
BraceWrapping:
  AfterFunction: false
AllowShortBlocksOnASingleLine: false
AllowShortLoopsOnASingleLine: false
```

and it was (correctly but by chance) formatted to:
```
while (true) {
  f();
}
/*comment*/ while (true) {
  f();
}
```

when using enabling brace wrapping after functions:
```
BasedOnStyle: LLVM
BreakBeforeBraces: Custom
BraceWrapping:
  AfterFunction: true
AllowShortBlocksOnASingleLine: false
AllowShortLoopsOnASingleLine: false
```

Reviewed By: MyDeveloperDay, HazardyKnusperkeks, owenpan

Differential Revision: https://reviews.llvm.org/D119649
2022-02-13 21:22:17 +01:00
Marek Kurdej
23f27850b1 [clang-format] Avoid multiple calls to FormatToken::getNextNonComment(). NFC. 2022-02-11 15:20:11 +01:00
Björn Schäpers
3d0b619261 [clang-format][NFC] Code Tidies in UnwrappedLineFormatter
* 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
2022-02-03 22:55:27 +01:00
Marek Kurdej
ca0d97072e [clang-format] Avoid merging macro definitions.
Fixes https://github.com/llvm/llvm-project/issues/42087.

Reviewed By: HazardyKnusperkeks, owenpan

Differential Revision: https://reviews.llvm.org/D118879
2022-02-03 18:54:46 +01:00
Marek Kurdej
d079995dd0 [clang-format] Elide unnecessary braces. NFC. 2022-02-02 15:28:53 +01:00
Marek Kurdej
574ad2a846 [clang-format] Use prefix operator--. NFC. 2022-02-02 14:01:48 +01:00
Philip Sigillito
d1aed486ef [clang-format] Handle C variables with name that matches c++ access specifier
Reviewed By: MyDeveloperDay, curdeius, HazardyKnusperkeks

Differential Revision: https://reviews.llvm.org/D117416
2022-01-30 20:56:50 +01:00
Marek Kurdej
36622c4e1a [clang-format] Fix AllowShortFunctionsOnASingleLine: InlineOnly with wrapping after record.
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
2022-01-27 18:06:31 +01:00