Summary:
The following C++ code was being detected by
`guessLanguage()` as Objective-C:
#define FOO(...) auto bar = [] __VA_ARGS__;
This was because `[] __VA_ARGS__` is not currently detected as a C++
lambda expression (it has no parens or braces), so
`TokenAnnotator::parseSquare()` incorrectly treats the opening square
as an ObjC method expression.
We have two options to fix this:
1. Parse `[] __VA_ARGS__` explicitly as a C++ lambda
2. Make it so `[]` is never parsed as an Objective-C method expression
This diff implements option 2, which causes the `[` to be parsed
as `TT_ArraySubscriptLSquare` instead of `TT_ObjCMethodExpr`.
Note that when I fixed this, it caused one change in formatting
behavior, where the following was implicitly relying on the `[`
being parsed as `TT_ObjCMethodExpr`:
A<int * []> a;
becomes:
A<int *[]> a;
with `Style.PointerAlignment = Middle`.
I don't really know what the desired format is for this syntax; the
test was added by Janusz Sobczak and integrated by @djasper in
b511fe9818
.
I went ahead and changed the test for now.
Test Plan: New tests added. Ran tests with:
% make -j12 FormatTests && ./tools/clang/unittests/Format/FormatTests
Fixes: https://bugs.llvm.org/show_bug.cgi?id=36248
Reviewers: djasper, jolesiak
Reviewed By: djasper
Subscribers: klimek, cfe-commits, djasper
Differential Revision: https://reviews.llvm.org/D45169
llvm-svn: 329070
Summary:
D44816 attempted to fix a few cases where `clang-format` incorrectly
inserted a space before the closing brace of an Objective-C dictionary
literal.
This revealed there were still a few cases where we inserted a space
after the opening brace of an Objective-C dictionary literal.
This fixes the formatting to be consistent and adds more tests.
Test Plan: New tests added. Confirmed tests failed before
diff and passed after diff.
Ran tests with:
% make -j12 FormatTests && ./tools/clang/unittests/Format/FormatTests
Reviewers: djasper, jolesiak, krasimir
Reviewed By: djasper
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D45168
llvm-svn: 329069
Summary:
In D43121, @Typz introduced logic to avoid indenting 2-or-more
argument ObjC selectors too far to the right if the first component
of the selector was longer than the others.
This had a small side effect of causing wrapped ObjC selectors with
exactly 1 argument to not obey IndentWrappedFunctionNames:
```
- (aaaaaaaaaa)
aaaaaaaaaa;
```
This diff fixes the issue by ensuring we align wrapped 1-argument
ObjC selectors correctly:
```
- (aaaaaaaaaa)
aaaaaaaaaa;
```
Test Plan: New tests added. Test failed before change, passed
after change. Ran tests with:
% make -j12 FormatTests && ./tools/clang/unittests/Format/FormatTests
Reviewers: djasper, klimek, Typz, jolesiak
Reviewed By: djasper, jolesiak
Subscribers: cfe-commits, Typz
Differential Revision: https://reviews.llvm.org/D44994
llvm-svn: 328871
r327219 added wrappers to std::sort which randomly shuffle the container before
sorting. This will help in uncovering non-determinism caused due to undefined
sorting order of objects having the same key.
To make use of that infrastructure we need to invoke llvm::sort instead of
std::sort.
llvm-svn: 328636
Summary:
This fixes an issue brought up by djasper@ in his review of D44790. We
handled top-level child lines, but if those child lines themselves
had child lines, we didn't handle them.
Rather than use recursion (which could blow out the stack), I use a
DenseSet to hold the set of lines we haven't yet checked (since order
doesn't matter), and update the set to add the children of each
line as we check it.
Test Plan: New tests added. Confirmed tests failed before fix
and passed after fix.
Reviewers: djasper
Reviewed By: djasper
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D44831
llvm-svn: 328628
Summary:
Previously, `clang-format` would sometimes insert a space
before the closing brace in an Objective-C dictionary literal.
Unlike array literals (which obey `Style.SpacesInContainerLiterals`
to add a space after `[` and before `]`), Objective-C dictionary
literals currently are not meant to insert a space after `{` and before
`}`, regardless of `Style.SpacesInContainerLiterals`.
However, some constructs like `@{foo : @(bar)}` caused `clang-format`
to insert a space between `)` and `}`.
This fixes the issue and adds tests. (I understand the behavior is
not consistent between array literals and dictionary literals, but
that's existing behavior that's a much larger change.)
Test Plan: New tests added. Ran tests with:
% make -j12 FormatTests && ./tools/clang/unittests/Format/FormatTests
Reviewers: djasper, jolesiak, Wizard
Reviewed By: djasper
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D44816
llvm-svn: 328627
Summary:
When I wrote `ObjCHeaderStyleGuesser`, I incorrectly assumed the
correct way to iterate over all tokens in `AnnotatedLine` was to
iterate over the linked list tokens starting with
`AnnotatedLine::First`.
However, `AnnotatedLine` also contains a vector
`AnnotedLine::Children` with child `AnnotedLine`s which have their own
tokens which we need to iterate over.
Because I didn't iterate over the tokens in the children lines, the
ObjC style guesser would fail on syntax like:
#define FOO ({ NSString *s = ... })
as the statement(s) inside { ... } are child lines.
This fixes the bug and adds a test. I confirmed the test
failed before the fix, and passed after the fix.
Test Plan: New tests added. Ran tests with:
% make -j12 FormatTests && ./tools/clang/unittests/Format/FormatTests
Reviewers: djasper, jolesiak, Wizard
Reviewed By: djasper
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D44790
llvm-svn: 328220
For multiline raw string literals, we generally want to respect the
author's choice of linebreak before the 'R"(' as the rest of the raw
string might be aligned to it and we cannot (commonly) modify the
content.
For single-line raw string literals, this doesn't make any sense and so
we should just treat them as regular string literals in this regard.
llvm-svn: 328201
When SpacesInParentheses is set to true clang-format does not add a
space before fully qualified names. For example:
do_something(::globalVar );
Fix by Darby Payne. Thank you!
llvm-svn: 328200
Summary:
We received reports of the Objective-C style guesser getting a false
negative on header files like:
CGSize SizeOfThing(MyThing thing);
This adds more Core Graphics identifiers to the Objective-C style
guesser.
Test Plan: New tests added. Ran tests with:
% make -j12 FormatTests && ./tools/clang/unittests/Format/FormatTests
Reviewers: jolesiak, djasper
Reviewed By: jolesiak, djasper
Subscribers: krasimir, klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D44632
llvm-svn: 328175
Summary:
Previously, clang-format would insert a space between
the closing parenthesis and 'new' in the following valid Objective-C
declaration:
+ (instancetype)new;
This was because 'new' is treated as a keyword, not an identifier.
TokenAnnotator::spaceRequiredBefore() already handled the case where
r_paren came before an identifier, so this diff extends it to
handle r_paren before 'new'.
Test Plan: New tests added. Ran tests with:
% make -j12 FormatTests && ./tools/clang/unittests/Format/FormatTests
Reviewers: djasper, jolesiak, stephanemoore
Reviewed By: djasper, jolesiak, stephanemoore
Subscribers: stephanemoore, klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D44692
llvm-svn: 328174
Summary:
Objective-C selectors with arguments take the form of:
foo:
foo:bar:
foo:bar:baz:
These can be passed to a macro, like NS_SWIFT_NAME():
https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html
and must never have spaces inserted around the colons.
Previously, there was logic in TokenAnnotator's tok::colon parser to
handle the single-argument case, but it failed for the
multiple-argument cases.
This diff fixes the bug and adds more tests.
Test Plan: New tests added. Ran tests with:
% make -j12 FormatTests && ./tools/clang/unittests/Format/FormatTests
Reviewers: jolesiak, djasper, Wizard
Reviewed By: jolesiak, Wizard
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D44638
llvm-svn: 327986
Summary:
This addresses bug 36766 and a FIXME in tests about empty lines before
`}[;] // comment` lines.
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D44631
llvm-svn: 327861
Summary: This disallows patterns like `[ext.name\n]` in text protos.
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D44569
llvm-svn: 327716
Summary: We weren't penalizing cases where the raw string prefix goes over the column limit.
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D44563
llvm-svn: 327708
Summary:
Previously, clang-format would detect the following as an
Objective-C block type:
FOO(^);
when it actually must be a C or C++ macro dealing with an XOR
statement or an XOR operator overload.
According to the Clang Block Language Spec:
https://clang.llvm.org/docs/BlockLanguageSpec.html
block types are of the form:
int (^)(char, float)
and block variables of block type are of the form:
void (^blockReturningVoidWithVoidArgument)(void);
int (^blockReturningIntWithIntAndCharArguments)(int, char);
void (^arrayOfTenBlocksReturningVoidWithIntArgument[10])(int);
This tightens up the detection so we don't unnecessarily detect
C macros which pass in the XOR operator.
Depends On D43904
Test Plan: New tests added. Ran tests with:
make -j12 FormatTests &&
./tools/clang/unittests/Format/FormatTests
Reviewers: krasimir, jolesiak, djasper
Reviewed By: djasper
Subscribers: djasper, cfe-commits, klimek
Differential Revision: https://reviews.llvm.org/D43906
llvm-svn: 327285
Summary:
Previously, clang-format would detect C++11 and C++17 attribute
specifiers like the following as Objective-C method invocations:
[[noreturn]];
[[clang::fallthrough]];
[[noreturn, deprecated("so sorry")]];
[[using gsl: suppress("type")]];
To fix this, I ported part of the logic from
tools/clang/lib/Parse/ParseTentative.cpp into TokenAnnotator.cpp so we
can explicitly parse and identify C++11 attribute specifiers.
This allows the guessLanguage() and getStyle() APIs to correctly
guess files containing the C++11 attribute specifiers as C++,
not Objective-C.
Test Plan: New tests added. Ran tests with:
make -j12 FormatTests && ./tools/clang/unittests/Format/FormatTests
Reviewers: krasimir, jolesiak, djasper
Reviewed By: djasper
Subscribers: aaron.ballman, cfe-commits, klimek
Differential Revision: https://reviews.llvm.org/D43902
llvm-svn: 327284
Three issues to fix:
- char_constants weren't properly treated as string literals
- Prevening the break after "label: " does not make sense in concunction
with AlwaysBreakBeforeMultilineStrings. It leads to situations where
clang-format just cannot find a viable format (it must break and yet
it must not break).
- AlwaysBreakBeforeMultilineStrings should not be on for LK_TextProto in
Google style.
llvm-svn: 327255
Summary:
This makes the formatter of raw string literals use NestedBlockIndent for
determining the 0 column of the content inside. This makes the formatting use
less horizonal space and fixes a case where two newlines before and after the
raw string prefix were selected instead of a single newline after it:
Before:
```
aaaa = ffff(
R"pb(
key: value)pb");
```
After:
```
aaaa = ffff(R"pb(
key: value)pb");
```
Reviewers: djasper, sammccall
Reviewed By: sammccall
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D44141
llvm-svn: 326996
Summary:
This patch fixes a bug where consecutive string literals in text protos were
put on the same line.
Reviewers: alexfh
Reviewed By: alexfh
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D44204
llvm-svn: 326945
Summary:
Previously, clang-format would detect the following as an
Objective-C for-in statement:
for (int x = in.value(); ...) {}
because the logic only decided a for-loop was definitely *not*
an Objective-C for-in loop after it saw a semicolon or a colon.
To fix this, I delayed the decision of whether this was a for-in
statement until after we found the matching right-paren, at which
point we know if we've seen a semicolon or not.
Test Plan: New tests added. Ran tests with:
make -j12 FormatTests && ./tools/clang/unittests/Format/FormatTests
Reviewers: krasimir, jolesiak
Reviewed By: jolesiak
Subscribers: djasper, cfe-commits, klimek
Differential Revision: https://reviews.llvm.org/D43904
llvm-svn: 326815
Summary:
Code that used to be formatted as `if (! + object) {` is now formatted as `if (!+object) {`
(we have a particular object in our codebase where unary `operator+` is overloaded to return the underlying value, which in this case is a `bool`)
We still preserve the TypeScript behavior where `!` is a trailing non-null operator. (This is already tested by an existing unit test in `FormatTestJS.cpp`)
It doesn't appear like handling of consecutive unary operators are tested in general, so I added another test for completeness
Patch contributed by @kevinl!
Reviewers: krasimir
Reviewed By: krasimir
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D43312
llvm-svn: 326792
Summary:
When disabled, this option allows removing the space before colon,
making it act more like the semi-colon. When enabled (default), the
current behavior is not affected.
This mostly affects C++11 loop, initializer list, inheritance list and
container literals:
class Foo: Bar {}
Foo::Foo(): a(a) {}
for (auto i: myList) {}
f({a: 1, b: 2, c: 3});
Reviewers: krasimir, djasper
Reviewed By: djasper
Subscribers: xvallspl, teemperor, karies, cfe-commits, klimek
Differential Revision: https://reviews.llvm.org/D32525
llvm-svn: 326426
Summary: This fixes a glitch where ``operator: value`` in a text proto would mess up the underlying formatting since it gets parsed as a kw_operator instead of an identifier.
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D43830
llvm-svn: 326227
Summary:
This fixes a few issues djasper@ brought up in his review of D43522.
Test Plan:
make -j12 FormatTests && ./tools/clang/unittests/Format/FormatTests
Reviewers: djasper
Reviewed By: djasper
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D43598
llvm-svn: 326205
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:
D43522 caused an assertion failure when getStyle() was called with
an empty filename:
P8065
This adds a test to reproduce the failure and fixes the issue by
ensuring we never pass an empty filename to
Environment::CreateVirtualEnvironment().
Test Plan: New test added. Ran test with:
% make -j12 FormatTests && ./tools/clang/unittests/Format/FormatTests
Before diff, test failed with P8065. Now, test passes.
Reviewers: vsapsai, jolesiak, krasimir
Reviewed By: vsapsai
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D43590
llvm-svn: 325722
Summary:
For clients which don't have a filesystem, calling getStyle() doesn't
make much sense (there's no .clang-format files to search for).
In this diff, I hoist out the language-guessing logic from getStyle()
and move it into a new API guessLanguage().
I also added support for guessing the language of files which have no
extension (they could be C++ or ObjC).
Test Plan: New tests added. Ran tests with:
% make -j12 FormatTests && ./tools/clang/unittests/Format/FormatTests
Reviewers: jolesiak, krasimir
Reviewed By: jolesiak, krasimir
Subscribers: klimek, cfe-commits, sammccall
Differential Revision: https://reviews.llvm.org/D43522
llvm-svn: 325691
Summary:
This fixes the detection of scope openers in text proto extensions; previously
they were not detected correctly leading to instances like:
```
msg {
[aa.bb
] {
key: value
}
}
```
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D43469
llvm-svn: 325513
Summary: This patch fixes a case where a proto message attribute is wrongly identified as an text proto extension.
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D43465
llvm-svn: 325509
Summary:
`of` is only a keyword when after an identifier, but not when after
an actual keyword.
Before:
return of (a, b, c);
After:
return of(a, b, c);
Reviewers: djasper
Subscribers: cfe-commits, klimek
Differential Revision: https://reviews.llvm.org/D43440
llvm-svn: 325489
Summary:
Frequently, a percent in protos denotes a formatting specifier for string replacement.
Thus it is desirable to keep the percent together with what follows after it.
Reviewers: djasper
Reviewed By: djasper
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D43294
llvm-svn: 325159
Summary: This patch fixes a bug where the comment indent of comments in text protos gets messed up because by default paren states get created with AlignColons = true (which makes snese for ObjC).
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D43194
llvm-svn: 324896
Summary:
When the target object expression is short and the first selector name
is long, clang-format used to break the colon alignment:
[I performSelectorOnMainThread:@selector(loadAccessories)
withObject:nil
waitUntilDone:false];
This happens because the colon is placed at `ContinuationIndent +
LongestObjCSelectorName`, so that any selector can be wrapped. This is
however not needed in case the longest selector is the firstone, and
not wrapped.
To overcome this, this patch does not include the first selector in
`LongestObjCSelectorName` computation (in TokenAnnotator), and lets
`ContinuationIndenter` decide how to account for the first selector
when wrapping. (Note this was already partly the case, see line 521
of ContinuationIndenter.cpp)
This way, the code gets properly aligned whenever possible without
breaking the continuation indent.
[I performSelectorOnMainThread:@selector(loadAccessories)
withObject:nil
waitUntilDone:false];
[I // force break
performSelectorOnMainThread:@selector(loadAccessories)
withObject:nil
waitUntilDone:false];
[I perform:@selector(loadAccessories)
withSelectorOnMainThread:true
waitUntilDone:false];
Reviewers: krasimir, djasper, klimek
Subscribers: cfe-commits
Differential Revision: https://reviews.llvm.org/D43121
llvm-svn: 324741
Summary:
Concatenating Objective-C string literals inside an array literal
raises the warning -Wobjc-string-concatenation (which is enabled by default).
clang-format currently splits and concatenates string literals like
the following:
NSArray *myArray = @[ @"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" ];
into:
NSArray *myArray =
@[ @"aaaaaaaaaaaaaaaaaaaaaaaaaaaa"
@"aaaaaaaaa" ];
which raises the warning. This is https://bugs.llvm.org/show_bug.cgi?id=36153 .
The options I can think of to fix this are:
1) Have clang-format disable Wobjc-string-concatenation by emitting
pragmas around the formatted code
2) Have clang-format wrap the string literals in a macro (which
disables the warning)
3) Disable string splitting for Objective-C string literals inside
array literals
I think 1) has no precedent, and I couldn't find a good
identity() macro for 2). So, this diff implements 3).
Test Plan: make -j12 FormatTests && ./tools/clang/unittests/Format/FormatTests
Reviewers: jolesiak, stephanemoore, djasper
Reviewed By: jolesiak
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D42704
llvm-svn: 324618
Summary:
This patch is a follow-up to r323319 (which disables string literal breaking for
text protos) and it disables breaking before long string literals.
For example this:
```
keyyyyy: "long string literal"
```
used to get broken into:
```
keyyyyy:
"long string literal"
```
While at it, I also enabled it for LK_Proto and fixed a bug in the mustBreak code.
Reviewers: djasper, sammccall
Reviewed By: djasper
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D42957
llvm-svn: 324591
Summary:
This is split off from D42650, and sets ObjCBinPackProtocolList
to Never for the google style.
Depends On D42650
Test Plan: New tests added. make -j12 FormatTests && ./tools/clang/unittests/Format/FormatTests
Reviewers: krasimir, jolesiak, stephanemoore
Reviewed By: krasimir, jolesiak, stephanemoore
Subscribers: klimek, cfe-commits, hokein, Wizard
Differential Revision: https://reviews.llvm.org/D42708
llvm-svn: 324553
Summary:
Fixes formatting of ObjC message arguments when inline block is a first
argument.
Having inline block as a first argument when method has multiple parameters is
discouraged by Apple:
"It’s best practice to use only one block argument to a method. If the
method also needs other non-block arguments, the block should come last"
(https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/WorkingwithBlocks/WorkingwithBlocks.html#//apple_ref/doc/uid/TP40011210-CH8-SW7),
it should be correctly formatted nevertheless.
Current formatting:
```
[object blockArgument:^{
a = 42;
}
anotherArg:42];
```
Fixed (colon alignment):
```
[object
blockArgument:^{
a = 42;
}
anotherArg:42];
```
Test Plan: make -j12 FormatTests && tools/clang/unittests/Format/FormatTests
Reviewers: krasimir, benhamilton
Reviewed By: krasimir, benhamilton
Subscribers: benhamilton, klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D42493
llvm-svn: 324469
Summary:
In r236412, @djasper added a comment:
// FIXME: We likely want to do this for more combinations of brackets.
// Verify that it is wanted for ObjC, too.
In D42650, @stephanemoore asked me to confirm this.
This followup to D42650 adds more tests to verify the relative
alignment behavior for Objective-C 2.0 generics passed to functions
and removes the second half of the FIXME comment.
Test Plan:
make -j12 FormatTests && \
./tools/clang/unittests/Format/FormatTests --gtest_filter=FormatTestObjC.\*
Reviewers: stephanemoore, jolesiak, djasper
Reviewed By: jolesiak
Subscribers: klimek, cfe-commits, djasper, stephanemoore, krasimir
Differential Revision: https://reviews.llvm.org/D42864
llvm-svn: 324364
Summary:
This patch adds spaces around angle brackets in text proto Google style.
Previously these were detected as template openers and closers, which happened
to have the expected effect. Now we detect them as scope openers and closers
similarly to the way braces are handled in this context.
Reviewers: djasper
Reviewed By: djasper
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D42727
llvm-svn: 324337
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:
This is an alternative approach to D42014 after some
investigation by stephanemoore@ and myself.
Previously, the format parameter `BinPackParameters` controlled both
C function parameter list bin-packing and Objective-C protocol conformance
list bin-packing.
We found in the Google style, some teams were changing
`BinPackParameters` from its default (`true`) to `false` so they could
lay out Objective-C protocol conformance list items one-per-line
instead of bin-packing them into as few lines as possible.
To allow teams to use one-per-line Objective-C protocol lists without
changing bin-packing for other areas like C function parameter lists,
this diff introduces a new LibFormat parameter
`ObjCBinPackProtocolList` to control the behavior just for ObjC
protocol conformance lists.
The new parameter is an enum which defaults to `Auto` to keep the
previous behavior (delegating to `BinPackParameters`).
Depends On D42649
Test Plan: New tests added. make -j12 FormatTests && ./tools/clang/unittests/Format/FormatTests
Reviewers: jolesiak, stephanemoore, djasper
Reviewed By: stephanemoore
Subscribers: Wizard, hokein, cfe-commits, klimek
Differential Revision: https://reviews.llvm.org/D42650
llvm-svn: 324131
Summary:
r312125, which introduced preprocessor indentation, shipped with a known
issue where "indentation of comments immediately before indented
preprocessor lines is toggled on each run". For example these two forms
toggle:
#ifndef HEADER_H
#define HEADER_H
#if 1
// comment
# define A 0
#endif
#endif
#ifndef HEADER_H
#define HEADER_H
#if 1
// comment
# define A 0
#endif
#endif
This happens because we check vertical alignment against the '#' yet
indent to the level of the 'define'. This patch resolves this issue by
aligning against the '#'.
Reviewers: krasimir, klimek, djasper
Reviewed By: krasimir
Subscribers: cfe-commits
Differential Revision: https://reviews.llvm.org/D42408
llvm-svn: 323904
Summary:
This patch modifies the text proto Google style to add spaces around braces.
I investigated using something different than Cpp11BracedListStyle, but it turns out it's what we want and also the java and js styles also depend on that.
Reviewers: djasper
Reviewed By: djasper
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D42685
llvm-svn: 323860
Summary:
This disables some of the most commonly used text proto delimiters and functions
for google style until we resolve several style options for that style.
In particular, wheter there should be a space surrounding braces ``msg { sub { key : value } }``
and the extent of packing of submessages on a same line.
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D42651
llvm-svn: 323678
Summary:
JavaScript automatic semicolon insertion can trigger before [ and (, so
avoid breaking before them if the previous token is likely to terminate
an expression.
Reviewers: djasper
Subscribers: cfe-commits, klimek
Differential Revision: https://reviews.llvm.org/D42570
llvm-svn: 323532
Summary:
Consider the text proto:
```
message {
sub { key: value }
}
```
Previously the first `{` was TT_Unknown, which caused the inner message to be
indented by the continuation width. This didn't happen for:
```
message {
sub: { key: value }
}
```
This is because the code to mark the first `{` as a TT_DictLiteral was only
considering the case where it marches forward and reaches a `:`.
This patch updates this by looking not only for `:`, but also for `<` and `{`.
Reviewers: djasper
Reviewed By: djasper
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D42500
llvm-svn: 323419
Summary:
Commonly string literals in protos are already multiline, so breaking them
further is undesirable.
Reviewers: djasper
Reviewed By: djasper
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D42373
llvm-svn: 323319
Summary:
This patch fixes an issue where the UnbreakableTailLength would be counted towards
the length of a token during breaking, even though we can break after the token.
For example, this proto text with column limit 20
```
# ColumnLimit: 20 V
foo: {
bar: {
bazoo: "aaaaaaa"
}
}
```
was broken:
```
# ColumnLimit: 20 V
foo: {
bar: {
bazoo:
"aaaaaaa"
}
}
```
because the 2 closing `}` were counted towards the string literal's `UnbreakableTailLength`.
Reviewers: djasper
Reviewed By: djasper
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D42376
llvm-svn: 323188
Summary:
This patch adds canonical delimiter support to the raw string formatting.
This allows matching delimiters to be updated to the canonical one.
Reviewers: bkramer
Reviewed By: bkramer
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D42187
llvm-svn: 322956
Summary:
This patch addresses bug 36002, where a combination of options causes the line
following a short block in macro to be merged with that macro.
Reviewers: bkramer
Reviewed By: bkramer
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D42298
llvm-svn: 322954
Summary:
The Google style guide is neutral on whether there should be a
space before the protocol list in an Objective-C @interface or
@implementation.
The majority of Objective-C code in both Apple's public
header files and Google's open-source uses a space before
the protocol list, so this changes the google style to
default ObjCSpaceBeforeProtocolList to true.
Test Plan: make -j12 FormatTests && ./tools/clang/unittests/Format/FormatTests
Reviewers: krasimir, djasper, klimek
Reviewed By: krasimir
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D41074
llvm-svn: 322873
Summary: This replaces an unordered_set from r322690 with an array and binary search.
Reviewers: bkramer, benhamilton
Reviewed By: bkramer, benhamilton
Subscribers: jolesiak, benhamilton, klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D42189
llvm-svn: 322749
Summary:
This improves upon the previous Objective-C header guessing heuristic
from rC320479.
Now, we run the lexer on C++ header files and look for Objective-C
keywords and syntax. We also look for Foundation types.
Test Plan: make -j12 FormatTests && ./tools/clang/unittests/Format/FormatTests
Reviewers: jolesiak, krasimir
Reviewed By: jolesiak
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D42135
llvm-svn: 322690
Summary:
This patch changes the structure for raw string formatting options by making it
language based (enumerate delimiters per language) as opposed to delimiter-based
(specify the language for a delimiter). The raw string formatting now uses an
appropriate style from the .clang-format file, if exists.
Reviewers: bkramer
Reviewed By: bkramer
Subscribers: cfe-commits, klimek
Differential Revision: https://reviews.llvm.org/D42098
llvm-svn: 322634
Summary:
This patch adds a FormatStyleSet for storing per-language FormatStyles for the
purposes of formatting code blocks inside the main code.
Reviewers: bkramer
Reviewed By: bkramer
Subscribers: klimek, djasper, bkramer, cfe-commits
Differential Revision: https://reviews.llvm.org/D41487
llvm-svn: 322479
This reverts commit 37e69667f748e1458b46483b7c1b8f9ba33eec44.
We're going to discuss its ramifications further before making a
conclusion.
llvm-svn: 320747
Summary:
If we write the following code, it goes over 100 columns, so we need to wrap it:
```
- (VeryLongReturnTypeName)veryLongMethodParameter:(VeryLongParameterName)thisIsAVeryLongParameterName
longMethodParameter:(LongParameterName)thisIsAlsoAnotherLongParameterName;
```
Currently, clang-format with the google style aligns the method parameter names on the first column:
```
- (VeryLongReturnTypeName)
veryLongMethodParameter:(VeryLongParameterName)thisIsAVeryLongParameterName
longMethodParameter:(LongParameterName)thisIsAlsoAnotherLongParameterName;
```
We'd like clang-format in the google style to align these to column 4 for Objective-C:
```
- (VeryLongReturnTypeName)
veryLongMethodParameter:(VeryLongParameterName)thisIsAVeryLongParameterName
longMethodParameter:(LongParameterName)thisIsAlsoAnotherLongParameterName;
```
Test Plan: make -j12 FormatTests && ./tools/clang/unittests/Format/FormatTests
Reviewers: krasimir, djasper, klimek
Reviewed By: djasper
Subscribers: cfe-commits, thakis
Differential Revision: https://reviews.llvm.org/D41195
llvm-svn: 320714
Adding the new enumerator forced a bunch more changes into this patch than I
would have liked. The -Wtautological-compare warning was extended to properly
check the new comparison operator, clang-format needed updating because it uses
precedence levels as weights for determining where to break lines (and several
operators increased their precedence levels with this change), thread-safety
analysis needed changes to build its own IL properly for the new operator.
All "real" semantic checking for this operator has been deferred to a future
patch. For now, we use the relational comparison rules and arbitrarily give
the builtin form of the operator a return type of 'void'.
llvm-svn: 320707
This patch improves detection of ObjC header files.
Right now many ObjC headers, especially short ones, are categorized as C/C++.
Way of filtering still isn't the best, as most likely it should be token-based.
Contributed by jolesiak!
llvm-svn: 320479
Before, we would not break:
int a = foo(/* trailing */);
when the end of /* trailing */ was exactly the column limit; the reason
is that block comments can have an unbreakable tail length - in this case
2, for the trailing ");"; we would unconditionally account that when
calculating the column state at the end of the token, but not correctly
add it into the remaining column length before, as we do for string
literals.
The fix is to correctly account the trailing unbreakable sequence length
into our formatting decisions for block comments. Line comments cannot
have a trailing unbreakable sequence, so no change is needed for them.
llvm-svn: 319642
When we break a long line like:
Column limit: 21
|
// foo foo foo foo foo foo foo foo foo foo foo foo
The local decision when to allow protruding vs. breaking can lead to this
outcome (2 excess characters, 2 breaks):
// foo foo foo foo foo
// foo foo foo foo foo
// foo foo
While strictly staying within the column limit leads to this strictly better
outcome (fully below the column limit, 2 breaks):
// foo foo foo foo
// foo foo foo foo
// foo foo foo foo
To get an optimal solution, we would need to consider all combinations of excess
characters vs. breaking for all lines, but that would lead to a significant
increase in the search space of the algorithm for little gain.
Instead, we blindly try both approches and·select the one that leads to the
overall lower penalty.
Differential Revision: https://reviews.llvm.org/D40605
llvm-svn: 319541
This fixes some bugs in the reflowing logic and splits out the concerns
of reflowing from BreakableToken.
Things to do after this patch:
- Refactor the breakProtrudingToken function possibly into a class, so we
can split it up into methods that operate on the common state.
- Optimize whitespace compression when reflowing by using the next possible
split point instead of the latest possible split point.
- Retry different strategies for reflowing (strictly staying below the
column limit vs. allowing excess characters if possible).
Differential Revision: https://reviews.llvm.org/D40310
llvm-svn: 319314
Summary:
This patch allows grouping multiple #include blocks together and sort all includes as one big block.
Additionally, sorted includes can be regrouped after sorting based on configured categories.
Contributed by @KrzysztofKapusta!
Reviewers: krasimir
Reviewed By: krasimir
Subscribers: cfe-commits, klimek
Differential Revision: https://reviews.llvm.org/D40288
llvm-svn: 319024
Summary:
clang-format does not collapse short records, interfaces, unions, etc.,
but fails to do so if the record is preceded by certain modifiers
(export, default, abstract, declare). This change skips over all
modifiers, and thus handles all record definitions uniformly.
Before:
export class Foo { bar: string; }
class Baz {
bam: string;
}
After:
export class Foo {
bar: string;
}
class Baz {
bam: string;
}
Reviewers: djasper
Subscribers: klimek
Differential Revision: https://reviews.llvm.org/D40430
llvm-svn: 318976
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:
Wrapping between the type name and the array type indicator creates
invalid syntax in TypeScript.
Before:
const xIsALongIdent:
YJustBarelyFitsLinex
[]; // illegal syntax.
After:
const xIsALongIdent:
YJustBarelyFitsLinex[];
Reviewers: djasper
Subscribers: klimek
Differential Revision: https://reviews.llvm.org/D40436
llvm-svn: 318959
Summary: The same rules apply as for `return`.
Reviewers: djasper
Subscribers: klimek
Differential Revision: https://reviews.llvm.org/D40431
llvm-svn: 318958
Summary:
Previously, clang-format would drop a space character between `of` and
then following (non-identifier) token if the preceding token was part of
a destructuring assignment (`}` or `]`).
Before:
for (const [a, b] of[]) {}
After:
for (const [a, b] of []) {}
Reviewers: djasper
Subscribers: klimek
Differential Revision: https://reviews.llvm.org/D40411
llvm-svn: 318942
Summary:
clang-format already removes empty lines at the beginning & end of
blocks:
int x() {
foo(); // lines before and after will be removed.
}
However because lamdas and arrow functions are parsed as expressions,
the existing logic to remove empty lines in UnwrappedLineFormatter
doesn't handle them.
This change special cases arrow functions in ContinuationIndenter to
remove empty lines:
x = []() {
foo(); // lines before and after will now be removed.
};
Reviewers: djasper
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D40178
llvm-svn: 318537
For each line that we break in a protruding token, compute whether the
penalty of breaking is actually larger than the penalty of the excess
characters. Only break if that is the case.
llvm-svn: 318515
Create more orthogonal pieces. The restructuring made it easy to try out
several alternatives to D33589, and while none of the alternatives
turned out to be the right solution, the underlying simplification of
the structure is helpful.
Differential Revision: https://reviews.llvm.org/D39900
llvm-svn: 318141
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
Summary:
This makes clang-format sort using declarations case-sensitive with the
exception that '_' comes just before 'A'. This is better than the current case
insensitive version, because it groups uppercase names in the same namespace
together.
Reviewers: bkramer
Reviewed By: bkramer
Subscribers: cfe-commits, klimek
Differential Revision: https://reviews.llvm.org/D39549
llvm-svn: 317325
Summary:
This patch makes the implementation of parseUnaryOperator non-recursive. We had
a problem with a file starting with tens of thousands of +'es and -'es which
caused clang-format to stack overflow.
Reviewers: bkramer
Reviewed By: bkramer
Subscribers: cfe-commits, klimek
Differential Revision: https://reviews.llvm.org/D39498
llvm-svn: 317113
Summary:
This patch enables sorting the full block of using declarations when
some line is affected.
Reviewers: djasper
Reviewed By: djasper
Subscribers: cfe-commits, klimek
Differential Revision: https://reviews.llvm.org/D39024
llvm-svn: 316130
Summary:
This patch enables `BreakableToken` to manage the formatting of non-trailing
block comments. It is a refinement of https://reviews.llvm.org/D37007.
We discovered that the optimizer outsmarts us on cases where breaking the comment
costs considerably less than breaking after the comment. This patch addresses
this by ensuring that a newline is inserted between a block comment and the next
token.
Reviewers: djasper
Reviewed By: djasper
Subscribers: cfe-commits, klimek
Differential Revision: https://reviews.llvm.org/D37695
llvm-svn: 315893
Summary:
This patch fixes a regression introduced in r312904, where the formatter confuses
the `else` in `#else` with an `else` of an `if-else` statement.
For example, formatting this code with google style
```
#ifdef A
int f() {}
#else
int f() {}
#endif
```
resulted in
```
#ifdef A
int f() {}
#else
int f() {
}
#endif
```
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D37973
llvm-svn: 314683
https://reviews.llvm.org/rL299952 merged '>>>' tokens into a single
JavaRightLogicalShift token. This broke formatting of generics nested more than
two deep, e.g. Foo<Bar<Baz>>> because the '>>>' now weren't three '>' for
parseAngle().
Luckily, just deleting JavaRightLogicalShift fixes things without breaking the
test added in r299952, so do that.
https://reviews.llvm.org/D38291
llvm-svn: 314325
Summary:
NamespaceEndCommentsFixer did not fix namespace comments when the brace opening the namespace was not on the same line as the "namespace" keyword.
It occurs in Allman, GNU and Linux styles and whenever BraceWrapping.AfterNamespace is true.
Before:
```lang=cpp
namespace a
{
void f();
void g();
}
```
After:
```lang=cpp
namespace a
{
void f();
void g();
} // namespace a
```
Reviewers: krasimir
Reviewed By: krasimir
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D37904
llvm-svn: 314279
Keep space before or after the &/&& tokens, but not both. For example,
auto [x,y] = a;
auto &[xr, yr] = a; // LLVM style
auto& [xr, yr] = a; // google style
Differential Revision:https://reviews.llvm.org/D35743
llvm-svn: 314264
Summary: This adds an ext/ header include category for google style.
Reviewers: djasper
Reviewed By: djasper
Subscribers: cfe-commits, klimek
Differential Revision: https://reviews.llvm.org/D38243
llvm-svn: 314211
Summary:
This ignores case while sorting using-declarations, fixing a case where `_` would appear between lowercase and uppercase characters.
It also applies stable sort, so that replacements for the exact same using declarations are not generated.
Reviewers: klimek, alexfh
Reviewed By: alexfh
Subscribers: cfe-commits
Differential Revision: https://reviews.llvm.org/D37263
llvm-svn: 313963
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:
While `goog.setTestOnly` usually appears in the imports section of a file, it is
not actually an import, and also usually doesn't take long parameters (nor
namespaces as a parameter, it's a description/message that should be wrapped).
This fixes a regression where a `goog.setTestOnly` call nested in a function was
not wrapped.
Reviewers: djasper
Subscribers: klimek
Differential Revision: https://reviews.llvm.org/D37685
llvm-svn: 312918
Summary:
**Short overview:**
Fixed bug: https://bugs.llvm.org/show_bug.cgi?id=34001
Clang-format bug resulting in a strange behavior of control statements short blocks. Different flags combinations do not guarantee expected result. Turned on option AllowShortBlocksOnASingleLine does not work as intended.
**Description of the problem:**
Cpp source file UnwrappedLineFormatter does not handle AllowShortBlocksOnASingleLine flag as it should. Putting a single-line control statement without any braces, clang-format works as expected (depending on AllowShortIfStatementOnASingleLine or AllowShortLoopsOnASingleLine value). Putting a single-line control statement in braces, we can observe strange and incorrect behavior.
Our short block is intercepted by tryFitMultipleLinesInOne function. The function returns a number of lines to be merged. Unfortunately, our control statement block is not covered properly. There are several if-return statements, but none of them handles our block. A block is identified by the line first token and by left and right braces. A function block works as expected, there is such an if-return statement doing proper job. A control statement block, from the other hand, falls into strange conditional construct, which depends on BraceWrapping.AfterFunction flag (with condition that the line’s last token is left brace, what is possible in our case) or goes even further. That should definitely not happen.
**Description of the patch:**
By adding three different if statements, we guarantee that our short control statement block, however it looks like (different brace wrapping flags may be turned on), is handled properly and does not fall into wrong conditional construct. Depending on appropriate options we return either 0 (when something disturbs our merging attempt) or let another function (tryMergeSimpleBlock) take the responsibility of returned result (number of merged lines). Nevertheless, one more correction is required in mentioned tryMergeSimpleBlock function. The function, previously, returned either 0 or 2. The problem was that this did not handle the case when our block had the left brace in a separate line, not the header one. After change, after adding condition, we return the result compatible with block’s structure. In case of left brace in the header’s line we do everything as before the patch. In case of left brace in a separate line we do the job similar to the one we do in case of a “non-header left brace” function short block. To be precise, we try to merge the block ignoring the header line. Then, if success, we increment our returned result.
**After fix:**
**CONFIG:**
```
AllowShortBlocksOnASingleLine: true
AllowShortIfStatementsOnASingleLine: true
BreakBeforeBraces: Custom
BraceWrapping: {
AfterClass: true, AfterControlStatement: true, AfterEnum: true, AfterFunction: true, AfterNamespace: false, AfterStruct: true, AfterUnion: true, BeforeCatch: true, BeforeElse: true
}
```
**BEFORE:**
```
if (statement) doSomething();
if (statement) { doSomething(); }
if (statement) {
doSomething();
}
if (statement)
{
doSomething();
}
if (statement)
doSomething();
if (statement) {
doSomething1();
doSomething2();
}
```
**AFTER:**
```
if (statement) doSomething();
if (statement) { doSomething(); }
if (statement) { doSomething(); }
if (statement) { doSomething(); }
if (statement) doSomething();
if (statement)
{
doSomething1();
doSomething2();
}
```
Contributed by @PriMee!
Reviewers: krasimir, djasper
Reviewed By: krasimir
Subscribers: cfe-commits, klimek
Differential Revision: https://reviews.llvm.org/D37140
llvm-svn: 312904
This is a recommit of r312781; in some build configurations
variable names are omitted, so changed the new regression
test accordingly.
llvm-svn: 312794
This adds _Float16 as a source language type, which is a 16-bit floating point
type defined in C11 extension ISO/IEC TS 18661-3.
In follow up patches documentation and more tests will be added.
Differential Revision: https://reviews.llvm.org/D33719
llvm-svn: 312781
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:
This patch detects the leading '<' in likely xml files and stops formatting in
that case. A recent use of a Qt xml file with a .ts extension triggered this:
http://doc.qt.io/qt-4.8/linguist-ts-file-format.html
Reviewers: djasper
Reviewed By: djasper
Subscribers: sammccall, cfe-commits, klimek
Differential Revision: https://reviews.llvm.org/D37136
llvm-svn: 311999
Summary:
Bug: https://bugs.llvm.org/show_bug.cgi?id=34016 - **Typedef enum part**
**Problem:**
Clang format does not allow the flag **BraceWrapping.AfterEnum** control the case when our **enum** is preceded by **typedef** keyword (what is common in C language).
**Patch description:**
Added case to the **"AfterEnum"** flag when our enum does not start a line - is preceded by **typedef** keyword.
**After fix:**
**CONFIG:**
```
BreakBeforeBraces: Custom
BraceWrapping: {
AfterClass: true, AfterControlStatement: true, AfterEnum: true, AfterFunction: true, AfterNamespace: false, AfterStruct: true, AfterUnion: true, BeforeCatch: true, BeforeElse: true
}
```
**BEFORE:**
```
typedef enum
{
a,
b,
c
} SomeEnum;
```
**AFTER:**
```
typedef enum
{
a,
b,
c
} SomeEnum;
```
Contributed by @PriMee!
Reviewers: krasimir, djasper
Reviewed By: djasper
Subscribers: cfe-commits, klimek
Differential Revision: https://reviews.llvm.org/D37143
llvm-svn: 311998
Summary:
Previously, clang-format would try to wrap template string substitutions
by indenting relative to the openening `${`. This helped with
indenting structured strings, such as strings containing HTML, as the
substitutions would be aligned according to the structure of the string.
However it turns out that the overwhelming majority of template string +
substitution usages are for substitutions into non-structured strings,
e.g. URLs or just plain messages. For these situations, clang-format
would often produce very ugly indents, in particular for strings
containing no line breaks:
return `<a href='http://google3/${file}?l=${row}'>${file}</a>(${
row
},${
col
}): `;
This change makes clang-format indent template string substitutions as
if they were string concatenation operations. It wraps +4 on overlong
lines and keeps all operands on the same line:
return `<a href='http://google3/${file}?l=${row}'>${file}</a>(${
row},${col}): `;
While this breaks some lexical continuity between the `${` and `row}`
here, the overall effects are still a huge improvement, and users can
still manually break the string using `+` if desired.
Reviewers: djasper
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D37142
llvm-svn: 311988
alignments
Indent should be compared before nesting level to determine if a token
is on the same scope as the one we align with. Because it was inverted,
clang-format sometimes tried to align tokens with tokens from outer
scopes, causing the assert(Shift >= 0) to fire.
This fixes bug #33507. Patch by Beren Minor, thank you!
llvm-svn: 311792
Summary:
This recommits https://reviews.llvm.org/D36956 with an update to the added test
case to not use raw string literals, since this makes gcc unhappy.
Reviewers: djasper
Reviewed By: djasper
Subscribers: cfe-commits, klimek
Differential Revision: https://reviews.llvm.org/D37109
llvm-svn: 311672
This reverts commit r311457. It reveals some dormant bugs in comment
reflowing, like breaking a single line jsdoc type annotation before a
parameter into multiple lines.
llvm-svn: 311641
Summary:
This patch makes the splits emitted for the beginning of comment lines during
reformatting absolute. Previously, they were relative to the start of the
non-whitespace content of the line, which messes up further TailOffset
calculations in breakProtrudingToken. This fixes an assertion failure reported
in bug 34236: https://bugs.llvm.org/show_bug.cgi?id=34236.
Reviewers: djasper
Reviewed By: djasper
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D36956
llvm-svn: 311559
Summary:
ColumnLimit = 0 means no limit, so comment should always be aligned if requested. This was broken with
https://llvm.org/svn/llvm-project/cfe/trunk@304687
introduced via
https://reviews.llvm.org/D33830
and is included in 5.0.0-rc2. This commit fixes it and adds a unittest for this property.
Should go into clang-5.0 IMHO.
Contributed by @pboettch!
Reviewers: djasper, krasimir
Reviewed By: djasper, krasimir
Subscribers: hans, klimek
Differential Revision: https://reviews.llvm.org/D36967
llvm-svn: 311532
Summary:
This patch is an alternative to https://reviews.llvm.org/D36614, by resolving a
non-idempotency issue by breaking non-trailing comments:
Consider formatting the following code with column limit at `V`:
```
V
const /* comment comment */ A = B;
```
The comment is not a trailing comment, breaking before it doesn't bring it under
the column limit. The formatter breaks after it, resulting in:
```
V
const /* comment comment */
A = B;
```
For a next reformat, the formatter considers the comment as a trailing comment,
so it is free to break it further, resulting in:
```
V
const /* comment
comment */
A = B;
```
This patch improves the situation by directly producing the third case.
Reviewers: djasper
Reviewed By: djasper
Subscribers: cfe-commits, klimek
Differential Revision: https://reviews.llvm.org/D37007
llvm-svn: 311457
Summary:
clang-format wraps object literal keys in an object literal if they are
marked as `TT_SelectorName`s and/or the colon is marked as
`TT_DictLiteral`. Previously, clang-format would accidentally work
because colons in type aliases were marked as `TT_DictLiteral`. r310367
fixed this to assing `TT_JsTypeColon`, which broke wrapping in certain
situations. However the root cause was that clang-format incorrectly
didn't skip questionmarks when detecting selector name.
This change fixes both locations to (1) assign `TT_SelectorName` and (2)
treat `TT_JsTypeColon` like `TT_DictLiteral`.
Previously:
type X = {
a: string, b?: string,
};
Now:
type X = {
a: string,
b?: string,
};
Reviewers: djasper, sammccall
Subscribers: cfe-commits, klimek
Differential Revision: https://reviews.llvm.org/D36684
llvm-svn: 310852