]> granicus.if.org Git - clang/commitdiff
[clang-format] fix handling of consecutive unary operators
authorKrasimir Georgiev <krasimir@google.com>
Tue, 6 Mar 2018 13:56:28 +0000 (13:56 +0000)
committerKrasimir Georgiev <krasimir@google.com>
Tue, 6 Mar 2018 13:56:28 +0000 (13:56 +0000)
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

git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@326792 91177308-0d34-0410-b5e6-96231b3b80d8

lib/Format/TokenAnnotator.cpp
unittests/Format/FormatTest.cpp
unittests/Format/FormatTestJS.cpp

index 4302ad4f6e925187582e8c61c2d0a2b410cfa9f3..d083cc7c33d9f704073b3205f576209da7709db8 100644 (file)
@@ -1531,10 +1531,8 @@ private:
     if (!PrevToken)
       return TT_UnaryOperator;
 
-    if (PrevToken->isOneOf(TT_CastRParen, TT_UnaryOperator) &&
-        !PrevToken->is(tok::exclaim))
-      // There aren't any trailing unary operators except for TypeScript's
-      // non-null operator (!). Thus, this must be squence of leading operators.
+    if (PrevToken->isOneOf(TT_CastRParen, TT_UnaryOperator))
+      // This must be a sequence of leading unary operators.
       return TT_UnaryOperator;
 
     // Use heuristics to recognize unary operators.
index eead11f55f9f614b446d8270594099dd8e60f059..c0117215e6a5b75d9e98402dff09b0872c4cc4d3 100644 (file)
@@ -5655,6 +5655,8 @@ TEST_F(FormatTest, UnderstandsUnaryOperators) {
   verifyFormat("(a->f())++;");
   verifyFormat("a[42]++;");
   verifyFormat("if (!(a->f())) {\n}");
+  verifyFormat("if (!+i) {\n}");
+  verifyFormat("~&a;");
 
   verifyFormat("a-- > b;");
   verifyFormat("b ? -a : c;");
index b9983f5c6e0482c424cb52b385608fe8accc407d..5fb47a7d32f0b0f09df8519ee4f2f3b7c347a985 100644 (file)
@@ -2133,6 +2133,7 @@ TEST_F(FormatTestJS, NonNullAssertionOperator) {
   verifyFormat("let x = foo!.bar();\n");
   verifyFormat("let x = foo ? bar! : baz;\n");
   verifyFormat("let x = !foo;\n");
+  verifyFormat("if (!+a) {\n}");
   verifyFormat("let x = foo[0]!;\n");
   verifyFormat("let x = (foo)!;\n");
   verifyFormat("let x = x(foo!);\n");