Summary:
Currently, `UnwrappedLineParser` thinks an arrow token after
an ObjC method expression is a C++ lambda arrow, so it formats:
```
[foo bar]->baz
```
as:
```
[foo bar] -> baz
```
Because `UnwrappedLineParser` runs before `TokenAnnotator`, it can't
know if the arrow token is after an ObjC method expression or not.
This diff makes `TokenAnnotator` remove the TT_LambdaArrow on
the arrow token if it follows an ObjC method expression.
Test Plan: New test added. Ran test with:
% ninja FormatTests && ./tools/clang/unittests/Format/FormatTests
Confirmed test failed before diff and passed after diff.
Reviewers: krasimir, djasper, sammccall
Reviewed By: sammccall
Subscribers: cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D57923
llvm-svn: 353531
to reflect the new license.
We understand that people may be surprised that we're moving the header
entirely to discuss the new license. We checked this carefully with the
Foundation's lawyer and we believe this is the correct approach.
Essentially, all code in the project is now made available by the LLVM
project under our new license, so you will see that the license headers
include that license only. Some of our contributors have contributed
code under our old license, and accordingly, we have retained a copy of
our old license notice in the top-level files in each project and
repository.
llvm-svn: 351636
Previously, Java annotation declarations (@interface AnnotationName) were being
handled as ObjC interfaces. This caused the brace formatting to mess up, so
that when you had a class with an interface defined in it, it would indent the
final brace of the class.
It used to format this class like so:
class A {
@interface B {}
}
But will now just skip the @interface and format it like so:
class A {
@interface B {}
}
Patch by Sam Maier!
Differential Revision: https://reviews.llvm.org/D53434
llvm-svn: 344789
Summary:
Some macros are used in the body of function, and actually contain the trailing semicolon: they should thus be automatically followed by a new line, and not get merged with the next line. This is for example the case with Qt's Q_UNUSED macro:
void foo(int a, int b) {
Q_UNUSED(a)
return b;
}
This patch deals with these cases by introducing a new option to specify list of statement macros. This re-uses the system already in place for foreach macros, to ensure there is no impact on performance.
Reviewers: krasimir, djasper, klimek
Reviewed By: krasimir
Subscribers: acoomans, mgrang, alexfh, klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D33440
llvm-svn: 343602
This fixes formatting namespaces with preceding 'inline' and 'export' (Modules TS) specifiers.
This change fixes namespaces not being identified as such with preceding 'inline' or 'export' specifiers.
Motivation: I was experimenting with the Modules TS (-fmodules-ts) and found it would be useful if clang-format would correctly format 'export namespace'. While making the changes, I noticed that similar issues still exist with 'inline namespace', and addressed them as well.
Patch by Marco Elver!
Reviewers: klimek, djasper, owenpan, sammccall
Reviewed By: owenpan, sammccall
Subscribers: owenpan, cfe-commits
Differential Revision: https://reviews.llvm.org/D51036
llvm-svn: 341450
Summary:
The Bug was reported and fixed by Owen Pan. See the original bug report here: https://bugs.llvm.org/show_bug.cgi?id=38557
Patch by Owen Pan!
Reviewers: krasimir, djasper, klimek
Reviewed By: klimek
Subscribers: JonasToth, cfe-commits
Differential Revision: https://reviews.llvm.org/D50697
llvm-svn: 340624
Summary:
The case of end-of-file comments was formatted badly:
```
key: value
# end-of-file comment
```
This patch fixes that formatting:
```
key: value
# end-of-file comment
```
Subscribers: cfe-commits
Differential Revision: https://reviews.llvm.org/D48539
llvm-svn: 335449
ScopedMacroState injects its own EOF token under certain conditions, and the
returned token may be modified in several different locations. If multiple
reformat operations are started in different threads, then they will both see
the same fake EOF token, and may both try to modify it. This is a data race.
This bug was caught with tsan.
Reviewers: klimek
Subscribers: cfe-commits
Differential Revision: https://reviews.llvm.org/D47759
llvm-svn: 334801
Summary:
Please take a close look at this CL. I haven't touched much of
`UnwrappedLineParser` before, so I may have gotten things wrong.
Previously, clang-format would incorrectly format the following:
```
@implementation Foo
- (Class)class {
}
- (void)foo {
}
@end
```
as:
```
@implementation Foo
- (Class)class {
}
- (void)foo {
}
@end
```
The problem is whenever `UnwrappedLineParser::parseStructuralElement()`
sees any of the keywords `class`, `struct`, or `enum`, it calls
`parseRecord()` to parse them as a C/C++ record.
This causes subsequent lines to be parsed incorrectly, which
causes them to be indented incorrectly.
In Objective-C/Objective-C++, these keywords are valid selector
components.
This diff fixes the issue by explicitly handling `+` and `-` lines
inside `@implementation` / `@interface` / `@protocol` blocks
and parsing them as Objective-C methods.
Test Plan: New tests added. Ran tests with:
make -j16 FormatTests && ./tools/clang/unittests/Format/FormatTests
Reviewers: jolesiak, klimek
Reviewed By: jolesiak, klimek
Subscribers: klimek, cfe-commits, Wizard
Differential Revision: https://reviews.llvm.org/D47095
llvm-svn: 333553
The DEBUG() macro is very generic so it might clash with other projects.
The renaming was done as follows:
- git grep -l 'DEBUG' | xargs sed -i 's/\bDEBUG\s\?(/LLVM_DEBUG(/g'
- git diff -U0 master | ../clang/tools/clang-format/clang-format-diff.py -i -p1 -style LLVM
Explicitly avoided changing the strings in the clang-format tests.
Differential Revision: https://reviews.llvm.org/D44975
llvm-svn: 332350
This is similar to the LLVM change https://reviews.llvm.org/D46290.
We've been running doxygen with the autobrief option for a couple of
years now. This makes the \brief markers into our comments
redundant. Since they are a visual distraction and we don't want to
encourage more \brief markers in new code either, this patch removes
them all.
Patch produced by
for i in $(git grep -l '\@brief'); do perl -pi -e 's/\@brief //g' $i & done
for i in $(git grep -l '\\brief'); do perl -pi -e 's/\\brief //g' $i & done
Differential Revision: https://reviews.llvm.org/D46320
llvm-svn: 331834
This required a couple of yaks to be shaved:
1. MatchingOpeningBlockLineIndex was misused to also store the
closing index; instead, use a second variable, as this doesn't
work correctly for "} else {".
2. We needed to change the API of AffectedRangeManager to not
use iterators; we always passed in begin / end for the whole
container before, so there was no mismatch in generality.
3. We need an extra check to discontinue formatting at the top
level, as we now sometimes change the indent of the closing
brace, but want to bail out immediately afterwards, for
example:
void f() {
if (a) {
}
void g();
Previously:
void f() {
if (a) {
}
void g();
Now:
void f() {
if (a) {
}
void g();
Differential Revision: https://reviews.llvm.org/D45726
llvm-svn: 330573
Previously, we would format:
int a() { ... }
[[unused]] int b() { ... }
as...
int a() {} [[unused] int b() {}
Now we correctly format each on its own line.
Similarly, we would detect:
[[unused]] int b() { return 42; }
As a lambda and leave it on a single line, even if that was disallowed
by the format style.
llvm-svn: 329816
Summary:
Previously, `clang-format` didn't understand lightweight
Objective-C generics, which have the form:
```
@interface Foo <KeyType,
ValueTypeWithConstraint : Foo,
AnotherValueTypeWithGenericConstraint: Bar<Baz>, ... > ...
```
The lightweight generic specifier list appears before the base
class, if present, but because it starts with < like the protocol
specifier list, `UnwrappedLineParser` was getting confused and
failed to parse interfaces with both generics and protocol lists:
```
@interface Foo <KeyType> : NSObject <NSCopying>
```
Since the parsed line would be incomplete, the format result
would be very confused (e.g., https://bugs.llvm.org/show_bug.cgi?id=24381).
This fixes the issue by explicitly parsing the ObjC lightweight
generic conformance list, so the line is fully parsed.
Fixes: https://bugs.llvm.org/show_bug.cgi?id=24381
Test Plan: New tests added. Ran tests with:
% make -j16 FormatTests && ./tools/clang/unittests/Format/FormatTests
Reviewers: djasper, jolesiak
Reviewed By: djasper
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D45185
llvm-svn: 329298
ObjC defines `@autoreleasepool` and `@synchronized` control blocks. These
used to be formatted according to the `AfterObjCDeclaration` brace-
wrapping flag, which is not very consistent.
This patch changes the behavior to use the `AfterControlStatement` flag
instead. This should not affect the behavior unless a custom brace
wrapping mode is used.
Reviewers: krasimir, djasper, klimek, benhamilton
Subscribers: cfe-commits
Differential Revision: https://reviews.llvm.org/D43232
llvm-svn: 326192
Summary:
The blocks used to be formatted using the "default" behavior, and would
thus be mistaken for function calls followed by blocks: this could lead
to unexpected inlining of the block and extra line-break before the
opening brace.
They are now formatted similarly to `@autoreleasepool` blocks, as
expected:
@synchronized(self) {
f();
}
Reviewers: krasimir, djasper, klimek
Subscribers: cfe-commits
Differential Revision: https://reviews.llvm.org/D43114
llvm-svn: 326191
Summary:
When a preprocessor indent closes after the last line of normal code we do not
correctly fixup include guard indents. For example:
#ifndef HEADER_H
#define HEADER_H
#if 1
int i;
# define A 0
#endif
#endif
incorrectly reformats to:
#ifndef HEADER_H
#define HEADER_H
#if 1
int i;
# define A 0
# endif
#endif
To resolve this issue we must fixup levels after parseFile(). Delaying
the fixup introduces a new state, so consolidate include guard search
state into an enum.
Reviewers: krasimir, klimek
Subscribers: cfe-commits
Differential Revision: https://reviews.llvm.org/D42035
llvm-svn: 324246
Summary:
When a preprocessor indent closes after the last line of normal code we do not
correctly fixup include guard indents. For example:
#ifndef HEADER_H
#define HEADER_H
#if 1
int i;
# define A 0
#endif
#endif
incorrectly reformats to:
#ifndef HEADER_H
#define HEADER_H
#if 1
int i;
# define A 0
# endif
#endif
To resolve this issue we must fixup levels after parseFile(). Delaying
the fixup introduces a new state, so consolidate include guard search
state into an enum.
Reviewers: krasimir, klimek
Reviewed By: krasimir
Subscribers: cfe-commits
Differential Revision: https://reviews.llvm.org/D42035
llvm-svn: 324238
Summary:
TypeScript generic type arguments can contain object (literal) types,
which in turn can contain semicolons:
const x: Array<{a: number; b: string;} = [];
Previously, clang-format would incorrectly categorize the braced list as
a block and terminate the line at the openening `{`, and then format the
entire expression badly.
With this change, clang-format recognizes `<` preceding a `{` as
introducing a type expression. In JS, `<` comparison with an object
literal can never be true, so the chance of introducing false positives
here is very low.
Reviewers: djasper
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D40424
llvm-svn: 318975
Summary:
Automatic Semicolon Insertion in clang-format tries to guess if a line
wrap should insert an implicit semicolong. The previous heuristic would
not trigger ASI if a token was immediately preceded by an `@` sign:
function foo(@Bar // <-- does not trigger due to preceding @
baz) {}
However decorators can have arbitrary parameters:
function foo(@Bar(param, param, param) // <-- precending @ missed
baz) {}
While it would be possible to precisely find the matching `@`, just
conversatively disabling ASI for the entire line is simpler, while also
not regressing ASI substatially.
Reviewers: djasper
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D40410
llvm-svn: 318973
Summary: This patch adds support for python-style comments in text protos.
Reviewers: djasper
Reviewed By: djasper
Subscribers: bkramer, cfe-commits, klimek
Differential Revision: https://reviews.llvm.org/D39806
llvm-svn: 317886
Correctly determine when [ is part of a structured binding instead of a
lambda.
To be able to reuse the implementation already available, this patch also:
- sets the Previous link of FormatTokens in the UnwrappedLineParser
- moves the isCppStructuredBinding function into FormatToken
Before:
auto const const &&[x, y] { A *i };
After:
auto const const && [x, y]{A * i};
Fixing formatting of the type of the structured binding is still missing.
llvm-svn: 313742
Most of the work was already done when we introduced a look-behind based
lambda introducer detection.
This patch finishes the transition by completely relying on the simple
lambda introducer detection and simply recursing into normal
brace-parsing code to parse until the end of the introducer.
This fixes initializers in lambdas, including nested lambdas.
Before:
auto a = [b = [c = 42]{}]{};
auto b = [c = &i + 23]{};
After:
auto a = [b = [c = 42] {}] {};
auto b = [c = &i + 23] {};
llvm-svn: 313622
Summary:
Bug: https://bugs.llvm.org/show_bug.cgi?id=34016 - **"extern C part"**
**Problem:**
Due to the lack of "brace wrapping extern" flag, clang format does parse the block after **extern** keyword moving the opening bracket to the header line always!
**Patch description:**
A new style added, new configuration flag - **BraceWrapping.AfterExternBlock** that allows us to decide whether we want a break before brace or not.
Reviewers: djasper, krasimir
Reviewed By: krasimir
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D37845
Contributed by @PriMee!
llvm-svn: 313354
Summary:
This is an implementation for [bug 17362](https://bugs.llvm.org/attachment.cgi?bugid=17362) which adds support for indenting preprocessor statements inside if/ifdef/endif. This takes previous work from fmauch (https://github.com/fmauch/clang/tree/preprocessor_indent) and makes it into a full feature.
The context of this patch is that I'm a VMware intern, and I implemented this because VMware needs the feature. As such, some decisions were made based on what VMware wants, and I would appreciate suggestions on expanding this if necessary to use-cases other people may want.
This adds a new enum config option, `IndentPPDirectives`. Values are:
* `PPDIS_None` (in config: `None`):
```
#if FOO
#if BAR
#include <foo>
#endif
#endif
```
* `PPDIS_AfterHash` (in config: `AfterHash`):
```
#if FOO
# if BAR
# include <foo>
# endif
#endif
```
This is meant to work whether spaces or tabs are used for indentation. Preprocessor indentation is independent of indentation for non-preprocessor lines.
Preprocessor indentation also attempts to ignore include guards with the checks:
1. Include guards cover the entire file
2. Include guards don't have `#else`
3. Include guards begin with
```
#ifndef <var>
#define <var>
```
This patch allows `UnwrappedLineParser::PPBranchLevel` to be decremented to -1 (the initial value is -1) so the variable can be used for indent tracking.
Defects:
* This patch does not handle the case where there's code between the `#ifndef` and `#define` but all other conditions hold. This is because when the #define line is parsed, `UnwrappedLineParser::Lines` doesn't hold the previous code line yet, so we can't detect it. This is out of the scope of this patch.
* This patch does not handle cases where legitimate lines may be outside an include guard. Examples are `#pragma once` and `#pragma GCC diagnostic`, or anything else that does not change the meaning of the file if it's included multiple times.
* This does not detect when there is a single non-preprocessor line in front of an include-guard-like structure where other conditions hold because `ScopedLineState` hides the line.
* Preprocessor indentation throws off `TokenAnnotator::setCommentLineLevels` so the indentation of comments immediately before indented preprocessor lines is toggled on each run. Fixing this issue appears to be a major change and too much complexity for this patch.
Contributed by @euhlmann!
Reviewers: djasper, klimek, krasimir
Reviewed By: djasper, krasimir
Subscribers: krasimir, mzeren-vmw, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D35955
llvm-svn: 312125
Summary: A closing parenthesis followed by a declaration or statement should always terminate the current statement.
Reviewers: djasper
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D36491
llvm-svn: 310482
Summary:
`case:` and `default:` would normally parse as labels for a `switch` block.
However in TypeScript, they can be used in field declarations, e.g.:
interface I {
case: string;
}
This change special cases parsing them in declaration lines to avoid wrapping
them.
Reviewers: djasper
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D36148
llvm-svn: 310070
Summary:
This patch fixes the parsing of proto option fields like `option op = <...>`.
Previously the parser did not enter the right code path inside the angle braces,
causing the contents to be split into several unwrapped lines inside.
I'll just go ahead and commit this since it's a straightforward bugfix.
Reviewers: djasper, klimek
Subscribers: cfe-commits
Differential Revision: https://reviews.llvm.org/D36217
llvm-svn: 309937
Summary:
clang-format would previously drop the whitespace after `extends` in code such as:
class Foo extends {} {}
Where the first set of curly braces is an inline object literal type.
Reviewers: djasper
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D36131
llvm-svn: 309695
Summary:
The current code would return an incorrect value when a preprocessor
directive is present immediately after the opening brace: this causes
the nanespace end comment fixer to break in some places, for exemple it
would not add the comment in this case:
namespace a {
#define FOO
}
Fixing the computation is simple enough, but it was breaking a feature,
as it would cause comments to be added also when the namespace
declaration was dependant on conditional compilation.
To fix this, a hash of the current preprocessor stack/branches is
computed at the beginning of parseBlock(), so that we explicitely do not
store the OpeningLineIndex when the beginning and end of the block are
not in the same preprocessor conditions.
Tthe hash is computed based on the line, but this could propbably be
improved by using the actual condition, so that clang-format would be
able to match multiple identical #ifdef blocks.
Reviewers: krasimir, djasper
Reviewed By: krasimir
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D35483
llvm-svn: 309369
Summary:
This fixes a regression exposed by r307795 and rL308725 in which the level of a
comment line between '} else {' and a preprocessor directive is incorrectly set
as the level of the '} else {' line. For example, this :
```
int f(int i) {
if (i) {
++i;
} else {
// comment
#ifdef A
--i;
#endif
}
}
```
was formatted as:
```
int f(int i) {
if (i) {
++i;
} else {
// comment
#ifdef A
--i;
#endif
}
}
```
Reviewers: djasper, klimek
Reviewed By: klimek
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D35794
llvm-svn: 308882
Summary:
This fixes a regression exposed by r307795 in which the level of a comment line
between '}' and a preprocessor directive is incorrectly set as the level of the
line before the '}'. In effect, this:
```
int f(int i) {
int j = i;
return i + j;
}
// comment
#ifdef A
#endif
```
was formatted as:
```
int f(int i) {
int j = i;
return i + j;
}
// comment
#ifdef A
#endif
```
Reviewers: djasper
Reviewed By: djasper
Subscribers: cfe-commits, klimek
Differential Revision: https://reviews.llvm.org/D35485
llvm-svn: 308725
Currently the `UnwrappedLineParser` fails to correctly unwrap JavaScript
imports where the module path is not on the same line as the `from` keyword.
For example:
import {A} from
'some/path/longer/than/column/limit/module.js';```
This causes issues when in the middle a list of imports because the formatter
thinks it has reached the end of the imports, and therefore will not sort any
imports lower in the list.
The formatter will, however, split the `from` keyword and the module path if
the path exceeds the column limit, which triggers the issue the next time the
file is formatted.
Patch originally by Jared Neil - thanks!
Differential Revision: https://reviews.llvm.org/D34920
llvm-svn: 308306
Summary:
This patch adds support for <>-style proto message fields inside proto options.
Previously these were wrongly treated as binary operators and as such were
working only by chance for a limited number of cases.
Reviewers: djasper
Reviewed By: djasper
Subscribers: cfe-commits, klimek
Differential Revision: https://reviews.llvm.org/D34621
llvm-svn: 306406
c++1z adds the following constructions to the language:
if constexpr (cond)
statement1;
else if constexpr (cond)
statement2;
else if constexpr (cond)
statement3;
else
statement4;
A first version of this was proposed in reviews.llvm.org/D26953 by
Francis Visoiu Mistrih, but never commited. This patch additionally
fixes the behavior when allowing short if statements on a single line
and was authored by Jacob Bandes-Storch. Thank you to both authors.
llvm-svn: 305666
Summary:
Add CompactNamespaces option, to pack namespace declarations on the
same line (somewhat similar to C++17 nested namespace definition).
With this option, consecutive namespace declarations are kept on the
same line:
namespace foo { namespace bar {
...
}} // namespace foo::bar
Reviewers: krasimir, djasper, klimek
Reviewed By: djasper
Subscribers: kimgr, cfe-commits, klimek
Tags: #clang-tools-extra
Differential Revision: https://reviews.llvm.org/D32480
llvm-svn: 305384