Summary:
Ensure the clang-format unit tests are themselves clang-formatted
Having areas of the llvm code which are clang-format clean, give us more areas to run new clang-format binaries on ensuring we haven't broken anything.
It seems to me we SHOULD have this clang-formatted at a minimum, otherwise how can we expect others to use clang-format if we "don't eat our own dogfood", also if the tests are dependent on the formatting of the code then that would also be bad!
Reviewed By: sammccall
Subscribers: cfe-commits
Tags: #clang, #clang-format
Differential Revision: https://reviews.llvm.org/D79204
Summary:
Even when BreakBeforeBinaryOperators is set, AlignOperands kept
aligning the beginning of the line, even when it could align the
actual operands (e.g. after an assignment).
With this patch, there is an option to actually align the operands, so
that the operator gets right-aligned with the equal sign or return
operator:
int aaaaa = bbbbbb
+ cccccc;
return aaaaaaa
&& bbbbbbb;
This not happen in parentheses, to avoid 'breaking' the indentation:
if (aaaaa
&& bbbbb)
return;
Reviewers: krasimir, djasper
Subscribers: cfe-commits, klimek
Differential Revision: https://reviews.llvm.org/D32478
Summary:
The previous change in https://reviews.llvm.org/D77311 attempted to
detect more C++ keywords. However it also precisely detected all
JavaScript keywords. That's generally correct, but many JavaScripy
keywords, e.g. `get`, are so-called pseudo-keywords. They can be used in
positions where a keyword would never be legal, e.g. in a dotted
expression:
x.type; // type is a pseudo-keyword, but can be used here.
x.get; // same for get etc.
This change introduces an additional parameter to
`IsJavaScriptIdentifier`, allowing clients to toggle whether they want
to allow `IdentifierName` tokens, i.e. pseudo-keywords.
Reviewers: krasimir
Subscribers: cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D77548
Summary:
C++ defines a number of keywords that are regular identifiers in
JavaScript, e.g. `concept`:
const concept = 1; // legit JS
This change expands the existing `IsJavaScriptIdentifier(Tok)` function
to return false for C++ keywords that aren't keywords in JS.
Reviewers: krasimir
Subscribers: jfb, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D77311
Summary:
This change adds an option to insert trailing commas into container
literals. For example, in JavaScript:
const x = [
a,
b,
^~~~~ inserted if missing.
]
This is implemented as a seperate post-processing pass after formatting
(because formatting might change whether the container literal does or
does not wrap). This keeps the code relatively simple and orthogonal,
though it has the notable drawback that the newly inserted comma is not
taken into account for formatting decisions (e.g. it might exceed the 80
char limit). To avoid exceeding the ColumnLimit, a comma is only
inserted if it fits into the limit.
Trailing comma insertion conceptually conflicts with argument
bin-packing: inserting a comma disables bin-packing, so we cannot do
both. clang-format rejects FormatStyle configurations that do both with
this change.
Reviewers: krasimir, MyDeveloperDay
Subscribers: cfe-commits
Tags: #clang
Summary:
clang-format currently always wraps the body of non-empty arrow
functions:
const x = () => {
z();
};
This change implements support for the `AllowShortLambdasOnASingleLine`
style options, controlling the indent style for arrow function bodies
that have one or fewer statements. SLS_All puts all on a single line,
SLS_Inline only arrow functions used in an inline position.
const x = () => { z(); };
Multi-statement arrow functions continue to be wrapped. Function
expressions (`a = function() {}`) and function/method declarations are
unaffected as well.
Reviewers: krasimir
Subscribers: cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D73335
Summary:
clang-format currently treats the nullish coalescing operator `??` like
the ternary operator. That causes multiple nullish terms to be each
indented relative to the last `??`, as they would in a ternary.
The `??` operator is often used in chains though, and as such more
similar to other binary operators, such as `||`. So to fix the indent,
set its token type to `||`, so it inherits the same treatment.
This opens up the question of operator precedence. However, `??` is
required to be parenthesized when mixed with `||` and `&&`, so this is
not a problem that can come up in syntactically legal code.
Reviewers: krasimir
Subscribers: cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D73026
Summary:
tslint and tsc (the TypeScript compiler itself) use comment pragmas of
the style:
// tslint:disable-next-line:foo
// @ts-ignore
These must not be wrapped and must stay on their own line, in isolation.
For tslint, this required adding it to the pragma regexp. The comments
starting with `@` are already left alone, but this change adds test
coverage for them.
Reviewers: krasimir
Subscribers: cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D72907
Summary:
Including `do`, `for`, and `while`, `if`, `else`, `try`, `catch`, in
addition to the previously handled fields. The unit test explicitly uses
methods, but this code path handles both fields and methods.
Reviewers: krasimir
Subscribers: cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D72827
Summary:
Adds tests to ensure that `async method() ...` does not wrap between async and
the method name, which would cause automatic semicolon insertion.
Reviewers: krasimir
Subscribers: cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D70377
Summary:
TypeScript now supports declaring fields:
class Foo {
declare field: string;
}
clang-format happens to already format this fine, so this change just
adds a regression test.
Reviewers: krasimir
Subscribers: cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D69972
Summary:
JavaScript / TypeScript is adding two new operators: the null
propagating operator `?.` and the nullish coalescing operator `??`.
const x = foo ?? 'default';
const z = foo?.bar?.baz;
This change adds support to lex and format both.
Reviewers: krasimir
Subscribers: cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D69971
Summary:
TypeScript 3.4 supports casting into a const type using `as const`:
const x = {x: 1} as const;
Previously, clang-format would insert a space after the `const`. With
this patch, no space is inserted after the sequence `as const`.
Reviewers: krasimir
Subscribers: cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D66736
llvm-svn: 369916
Addresses PR40999 https://bugs.llvm.org/show_bug.cgi?id=40999
Private fields and methods in JavaScript would get incorrectly indented
(it sees them as preprocessor directives and hence left aligns them)
In this revision `#identifier` tokens `tok::hash->tok::identifier` are
merged into a single new token `tok::identifier` with the `#` contained
inside the TokenText.
Before:
```
class Example {
pub = 1;
static pub2 = "foo";
static #priv2 = "bar";
method() { this.#priv = 5; }
static staticMethod() {
switch (this.#priv) {
case '1':
break;
}
}
this.#privateMethod(); // infinite loop
}
static #staticPrivateMethod() {}
}
```
After this fix the code will be correctly indented
```
class Example {
pub = 1;
#priv = 2;
static pub2 = "foo";
static #priv2 = "bar";
method() { this.#priv = 5; }
static staticMethod() {
switch (this.#priv) {
case '1':
#priv = 3;
break;
}
}
#privateMethod() {
this.#privateMethod(); // infinite loop
}
static #staticPrivateMethod() {}
}
```
NOTE: There might be some JavaScript code out there which uses the C
processor to preprocess .js files
http://www.nongnu.org/espresso/js-cpp.html. It's not clear how this
revision or even private fields and methods would interact.
Patch originally by MyDeveloperDays (thanks!).
llvm-svn: 356449
Before:
const x = veryLongIdentifier
`hello`;
After:
const x =
veryLongIdentifier`hello`;
While it's allowed to have the template string and tag identifier
separated by a line break, currently the clang-format output is not
stable when a break is forced. Additionally, disallowing a line break
makes it clear that the identifier is actually a tag for a template
string.
Patch originally by mitchellwills (thanks!).
llvm-svn: 356447
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
Summary:
It's a new primitive for importing symbols, and should be treated like
the (previously handled) `goog.require` and `goog.forwardDeclare`.
Reviewers: krasimir
Subscribers: cfe-commits
Differential Revision: https://reviews.llvm.org/D56385
llvm-svn: 350516
Summary:
Clang-format is treating all occurences of `is` in js as type matchers. In some
cases this is wrong, as it might be a dict key.
Reviewers: mprobst
Reviewed By: mprobst
Subscribers: cfe-commits
Differential Revision: https://reviews.llvm.org/D54753
llvm-svn: 347307
Summary:
This change adds some rudimentary support for conditional types.
Specifically it avoids breaking before `extends` and `infer` keywords,
which are subject to Automatic Semicolon Insertion, so breaking before
them creates incorrect syntax.
The actual formatting of the type expression is odd, but there is as of
yet no clear idea on how to format these.
See https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#conditional-types.
Reviewers: krasimir
Subscribers: cfe-commits
Differential Revision: https://reviews.llvm.org/D52536
llvm-svn: 343179
Summary:
This fixes a bug in clang-format where the last line's penalty is not
taken into account when its ending is broken. Usually the last line's penalty
is handled by addNextStateToQueue, but in cases where the trailing `*/` is put
on a newline, the contents of the last line have to be considered for penalizing.
Reviewers: mprobst
Reviewed By: mprobst
Subscribers: cfe-commits
Differential Revision: https://reviews.llvm.org/D50378
llvm-svn: 339123
Summary:
Previously, clang-format would avoid breaking before the first `{`
found, but then happily break before subsequent '{'s on the line. This
change fixes that by looking for the first location that has no opening
curly, if any.
This fixes the original commit by correcting the loop condition.
This reverts commit 66dc646e09b795b943668179c33d09da71a3b6bc.
Reviewers: krasimir
Subscribers: cfe-commits
Differential Revision: https://reviews.llvm.org/D50249
llvm-svn: 338890
Summary:
Previously, clang-format would avoid breaking before the first `{`
found, but then happily break before subsequent '{'s on the line. This
change fixes that by looking for the first location that has no opening
curly, if any.
Reviewers: krasimir
Subscribers: cfe-commits
Differential Revision: https://reviews.llvm.org/D50230
llvm-svn: 338837
Summary:
Previously, clang-format would crash if it tried to wrap an overlong
single line comment, because two parts of the code inserted a break in
the same location.
/** heregoesalongcommentwithnospace */
This wasn't previously noticed as it could only trigger for an overlong
single line comment that did have no breaking opportunities except for a
whitespace at the very beginning.
This also introduces a check for JavaScript to not ever wrap a comment
before an opening curly brace:
/** @mods {donotbreakbeforethecurly} */
This is because some machinery parsing these tags sometimes supports
breaks before a possible `{`, but in some other cases does not.
Previously clang-format was careful never to wrap a line with certain
tags on it. The better solution is to specifically disable wrapping
before the problematic token: this allows wrapping and aligning comments
but still avoids the problem.
Reviewers: krasimir
Subscribers: cfe-commits
Differential Revision: https://reviews.llvm.org/D50177
llvm-svn: 338706
Summary:
This patch makes clang-format indent the subsequent lines created by breaking a
long javadoc annotated line.
Reviewers: mprobst
Reviewed By: mprobst
Subscribers: acoomans, cfe-commits
Differential Revision: https://reviews.llvm.org/D49797
llvm-svn: 338232
Summary:
TypeScript uses the `!` token for strict property initialization
assertions, as in:
class X {
strictPropAsserted!: string;
}
Previously, clang-format would wrap between the `!` and the `:` for
overly long lines. This patch fixes that by generally preventing the
wrap in that location.
Reviewers: krasimir
Subscribers: cfe-commits
Differential Revision: https://reviews.llvm.org/D48030
llvm-svn: 334415
Summary:
`is` type annotations can occur at any nesting level. For example:
function x() {
return function y(): a is B { ... };
}
Breaking before the `is` above breaks TypeScript parsing the code. This
change prevents the wrap.
Reviewers: krasimir
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D47193
llvm-svn: 332968
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
Summary: Extend various verifyFormat helper functions to check that the
expected text is "stable". This provides some protection against bugs
where formatting results are ocilating between two forms, or continually
change in some other way.
Testing Done:
* Ran unit tests.
* Reproduced a known instability in preprocessor indentation which was
caught by this new check.
Reviewers: krasimir
Subscribers: cfe-commits
Differential Revision: https://reviews.llvm.org/D42034
llvm-svn: 329231
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:
`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:
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:
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
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:
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:
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
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
Summary:
In JavaScript, may keywords can be used in method names and thus call sites:
foo.delete();
foo.instanceof();
clang-format would previously insert whitespace after the `instanceof`. This
change generically skips inserting whitespace between a keyword and a
parenthesis if preceded by a dot, i.e. in a callsite.
Reviewers: djasper
Subscribers: klimek, cfe-commits
Differential Revision: https://reviews.llvm.org/D36142
llvm-svn: 310851
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