[clang] clang serialization unittests: fix some leaks (PR #82773)

2024-02-26 Thread Krasimir Georgiev via cfe-commits

https://github.com/krasimirgg closed 
https://github.com/llvm/llvm-project/pull/82773
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] clang serialization unittests: fix some leaks (PR #82773)

2024-02-26 Thread Krasimir Georgiev via cfe-commits

https://github.com/krasimirgg updated 
https://github.com/llvm/llvm-project/pull/82773

>From 43f8b15fa3e5465f1939d0359ff5dcfc83ed1717 Mon Sep 17 00:00:00 2001
From: Krasimir Georgiev 
Date: Fri, 23 Feb 2024 15:11:51 +
Subject: [PATCH 1/2] clang serialization unittests: fix some leaks

No functional changes intended.

Fixes some leaks found by running under asan with --gtest_repeat=2.
---
 .../Serialization/ModuleCacheTest.cpp  | 18 ++
 .../Serialization/VarDeclConstantInitTest.cpp  |  1 +
 2 files changed, 15 insertions(+), 4 deletions(-)

diff --git a/clang/unittests/Serialization/ModuleCacheTest.cpp 
b/clang/unittests/Serialization/ModuleCacheTest.cpp
index c3e347ffec660c..76aeee60f5a435 100644
--- a/clang/unittests/Serialization/ModuleCacheTest.cpp
+++ b/clang/unittests/Serialization/ModuleCacheTest.cpp
@@ -88,6 +88,16 @@ class ModuleCacheTest : public ::testing::Test {
 }
 )cpp");
   }
+ 
+  std::unique_ptr createInvocationAndEnableFree(
+  ArrayRef Args, CreateInvocationOptions Opts) {
+std::unique_ptr Invocation =
+createInvocation(Args, Opts);
+if (Invocation)
+  Invocation->getFrontendOpts().DisableFree = false;
+
+return Invocation;
+  }
 };
 
 TEST_F(ModuleCacheTest, CachedModuleNewPath) {
@@ -106,7 +116,7 @@ TEST_F(ModuleCacheTest, CachedModuleNewPath) {
 MCPArg.c_str(), "-working-directory", TestDir.c_str(),
 "test.m"};
   std::shared_ptr Invocation =
-  createInvocation(Args, CIOpts);
+  createInvocationAndEnableFree(Args, CIOpts);
   ASSERT_TRUE(Invocation);
   CompilerInstance Instance;
   Instance.setDiagnostics(Diags.get());
@@ -129,7 +139,7 @@ TEST_F(ModuleCacheTest, CachedModuleNewPath) {
  "-Fframeworks",  MCPArg.c_str(), "-working-directory",
  TestDir.c_str(), "test.m"};
   std::shared_ptr Invocation2 =
-  createInvocation(Args2, CIOpts);
+  createInvocationAndEnableFree(Args2, CIOpts);
   ASSERT_TRUE(Invocation2);
   CompilerInstance Instance2(Instance.getPCHContainerOperations(),
  ());
@@ -156,7 +166,7 @@ TEST_F(ModuleCacheTest, CachedModuleNewPathAllowErrors) {
 MCPArg.c_str(), "-working-directory", TestDir.c_str(),
 "test.m"};
   std::shared_ptr Invocation =
-  createInvocation(Args, CIOpts);
+  createInvocationAndEnableFree(Args, CIOpts);
   ASSERT_TRUE(Invocation);
   CompilerInstance Instance;
   Instance.setDiagnostics(Diags.get());
@@ -173,7 +183,7 @@ TEST_F(ModuleCacheTest, CachedModuleNewPathAllowErrors) {
   TestDir.c_str(), "-Xclang",  "-fallow-pcm-with-compiler-errors",
   "test.m"};
   std::shared_ptr Invocation2 =
-  createInvocation(Args2, CIOpts);
+  createInvocationAndEnableFree(Args2, CIOpts);
   ASSERT_TRUE(Invocation2);
   CompilerInstance Instance2(Instance.getPCHContainerOperations(),
  ());
diff --git a/clang/unittests/Serialization/VarDeclConstantInitTest.cpp 
b/clang/unittests/Serialization/VarDeclConstantInitTest.cpp
index 86ae929e7f17e4..7efa1c1d64a964 100644
--- a/clang/unittests/Serialization/VarDeclConstantInitTest.cpp
+++ b/clang/unittests/Serialization/VarDeclConstantInitTest.cpp
@@ -103,6 +103,7 @@ export namespace Fibonacci
   std::shared_ptr Invocation =
   createInvocation(Args, CIOpts);
   ASSERT_TRUE(Invocation);
+  Invocation->getFrontendOpts().DisableFree = false;
 
   CompilerInstance Instance;
   Instance.setDiagnostics(Diags.get());

>From 4ab1858f489d9222ce114bf8a351ac1e8012ec00 Mon Sep 17 00:00:00 2001
From: Krasimir Georgiev 
Date: Fri, 23 Feb 2024 15:20:32 +
Subject: [PATCH 2/2] reformat

---
 clang/unittests/Serialization/ModuleCacheTest.cpp | 7 ---
 1 file changed, 4 insertions(+), 3 deletions(-)

diff --git a/clang/unittests/Serialization/ModuleCacheTest.cpp 
b/clang/unittests/Serialization/ModuleCacheTest.cpp
index 76aeee60f5a435..a7ca98549b4125 100644
--- a/clang/unittests/Serialization/ModuleCacheTest.cpp
+++ b/clang/unittests/Serialization/ModuleCacheTest.cpp
@@ -88,9 +88,10 @@ class ModuleCacheTest : public ::testing::Test {
 }
 )cpp");
   }
- 
-  std::unique_ptr createInvocationAndEnableFree(
-  ArrayRef Args, CreateInvocationOptions Opts) {
+
+  std::unique_ptr
+  createInvocationAndEnableFree(ArrayRef Args,
+CreateInvocationOptions Opts) {
 std::unique_ptr Invocation =
 createInvocation(Args, Opts);
 if (Invocation)

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] clang serialization unittests: fix some leaks (PR #82773)

2024-02-23 Thread Krasimir Georgiev via cfe-commits

https://github.com/krasimirgg updated 
https://github.com/llvm/llvm-project/pull/82773

>From 43f8b15fa3e5465f1939d0359ff5dcfc83ed1717 Mon Sep 17 00:00:00 2001
From: Krasimir Georgiev 
Date: Fri, 23 Feb 2024 15:11:51 +
Subject: [PATCH 1/2] clang serialization unittests: fix some leaks

No functional changes intended.

Fixes some leaks found by running under asan with --gtest_repeat=2.
---
 .../Serialization/ModuleCacheTest.cpp  | 18 ++
 .../Serialization/VarDeclConstantInitTest.cpp  |  1 +
 2 files changed, 15 insertions(+), 4 deletions(-)

diff --git a/clang/unittests/Serialization/ModuleCacheTest.cpp 
b/clang/unittests/Serialization/ModuleCacheTest.cpp
index c3e347ffec660c..76aeee60f5a435 100644
--- a/clang/unittests/Serialization/ModuleCacheTest.cpp
+++ b/clang/unittests/Serialization/ModuleCacheTest.cpp
@@ -88,6 +88,16 @@ class ModuleCacheTest : public ::testing::Test {
 }
 )cpp");
   }
+ 
+  std::unique_ptr createInvocationAndEnableFree(
+  ArrayRef Args, CreateInvocationOptions Opts) {
+std::unique_ptr Invocation =
+createInvocation(Args, Opts);
+if (Invocation)
+  Invocation->getFrontendOpts().DisableFree = false;
+
+return Invocation;
+  }
 };
 
 TEST_F(ModuleCacheTest, CachedModuleNewPath) {
@@ -106,7 +116,7 @@ TEST_F(ModuleCacheTest, CachedModuleNewPath) {
 MCPArg.c_str(), "-working-directory", TestDir.c_str(),
 "test.m"};
   std::shared_ptr Invocation =
-  createInvocation(Args, CIOpts);
+  createInvocationAndEnableFree(Args, CIOpts);
   ASSERT_TRUE(Invocation);
   CompilerInstance Instance;
   Instance.setDiagnostics(Diags.get());
@@ -129,7 +139,7 @@ TEST_F(ModuleCacheTest, CachedModuleNewPath) {
  "-Fframeworks",  MCPArg.c_str(), "-working-directory",
  TestDir.c_str(), "test.m"};
   std::shared_ptr Invocation2 =
-  createInvocation(Args2, CIOpts);
+  createInvocationAndEnableFree(Args2, CIOpts);
   ASSERT_TRUE(Invocation2);
   CompilerInstance Instance2(Instance.getPCHContainerOperations(),
  ());
@@ -156,7 +166,7 @@ TEST_F(ModuleCacheTest, CachedModuleNewPathAllowErrors) {
 MCPArg.c_str(), "-working-directory", TestDir.c_str(),
 "test.m"};
   std::shared_ptr Invocation =
-  createInvocation(Args, CIOpts);
+  createInvocationAndEnableFree(Args, CIOpts);
   ASSERT_TRUE(Invocation);
   CompilerInstance Instance;
   Instance.setDiagnostics(Diags.get());
@@ -173,7 +183,7 @@ TEST_F(ModuleCacheTest, CachedModuleNewPathAllowErrors) {
   TestDir.c_str(), "-Xclang",  "-fallow-pcm-with-compiler-errors",
   "test.m"};
   std::shared_ptr Invocation2 =
-  createInvocation(Args2, CIOpts);
+  createInvocationAndEnableFree(Args2, CIOpts);
   ASSERT_TRUE(Invocation2);
   CompilerInstance Instance2(Instance.getPCHContainerOperations(),
  ());
diff --git a/clang/unittests/Serialization/VarDeclConstantInitTest.cpp 
b/clang/unittests/Serialization/VarDeclConstantInitTest.cpp
index 86ae929e7f17e4..7efa1c1d64a964 100644
--- a/clang/unittests/Serialization/VarDeclConstantInitTest.cpp
+++ b/clang/unittests/Serialization/VarDeclConstantInitTest.cpp
@@ -103,6 +103,7 @@ export namespace Fibonacci
   std::shared_ptr Invocation =
   createInvocation(Args, CIOpts);
   ASSERT_TRUE(Invocation);
+  Invocation->getFrontendOpts().DisableFree = false;
 
   CompilerInstance Instance;
   Instance.setDiagnostics(Diags.get());

>From 4ab1858f489d9222ce114bf8a351ac1e8012ec00 Mon Sep 17 00:00:00 2001
From: Krasimir Georgiev 
Date: Fri, 23 Feb 2024 15:20:32 +
Subject: [PATCH 2/2] reformat

---
 clang/unittests/Serialization/ModuleCacheTest.cpp | 7 ---
 1 file changed, 4 insertions(+), 3 deletions(-)

diff --git a/clang/unittests/Serialization/ModuleCacheTest.cpp 
b/clang/unittests/Serialization/ModuleCacheTest.cpp
index 76aeee60f5a435..a7ca98549b4125 100644
--- a/clang/unittests/Serialization/ModuleCacheTest.cpp
+++ b/clang/unittests/Serialization/ModuleCacheTest.cpp
@@ -88,9 +88,10 @@ class ModuleCacheTest : public ::testing::Test {
 }
 )cpp");
   }
- 
-  std::unique_ptr createInvocationAndEnableFree(
-  ArrayRef Args, CreateInvocationOptions Opts) {
+
+  std::unique_ptr
+  createInvocationAndEnableFree(ArrayRef Args,
+CreateInvocationOptions Opts) {
 std::unique_ptr Invocation =
 createInvocation(Args, Opts);
 if (Invocation)

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] clang serialization unittests: fix some leaks (PR #82773)

2024-02-23 Thread Krasimir Georgiev via cfe-commits

https://github.com/krasimirgg ready_for_review 
https://github.com/llvm/llvm-project/pull/82773
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] clang serialization unittests: fix some leaks (PR #82773)

2024-02-23 Thread Krasimir Georgiev via cfe-commits

https://github.com/krasimirgg created 
https://github.com/llvm/llvm-project/pull/82773

No functional changes intended.

Fixes some leaks found by running under asan with `--gtest_repeat=2`.

>From 43f8b15fa3e5465f1939d0359ff5dcfc83ed1717 Mon Sep 17 00:00:00 2001
From: Krasimir Georgiev 
Date: Fri, 23 Feb 2024 15:11:51 +
Subject: [PATCH] clang serialization unittests: fix some leaks

No functional changes intended.

Fixes some leaks found by running under asan with --gtest_repeat=2.
---
 .../Serialization/ModuleCacheTest.cpp  | 18 ++
 .../Serialization/VarDeclConstantInitTest.cpp  |  1 +
 2 files changed, 15 insertions(+), 4 deletions(-)

diff --git a/clang/unittests/Serialization/ModuleCacheTest.cpp 
b/clang/unittests/Serialization/ModuleCacheTest.cpp
index c3e347ffec660c..76aeee60f5a435 100644
--- a/clang/unittests/Serialization/ModuleCacheTest.cpp
+++ b/clang/unittests/Serialization/ModuleCacheTest.cpp
@@ -88,6 +88,16 @@ class ModuleCacheTest : public ::testing::Test {
 }
 )cpp");
   }
+ 
+  std::unique_ptr createInvocationAndEnableFree(
+  ArrayRef Args, CreateInvocationOptions Opts) {
+std::unique_ptr Invocation =
+createInvocation(Args, Opts);
+if (Invocation)
+  Invocation->getFrontendOpts().DisableFree = false;
+
+return Invocation;
+  }
 };
 
 TEST_F(ModuleCacheTest, CachedModuleNewPath) {
@@ -106,7 +116,7 @@ TEST_F(ModuleCacheTest, CachedModuleNewPath) {
 MCPArg.c_str(), "-working-directory", TestDir.c_str(),
 "test.m"};
   std::shared_ptr Invocation =
-  createInvocation(Args, CIOpts);
+  createInvocationAndEnableFree(Args, CIOpts);
   ASSERT_TRUE(Invocation);
   CompilerInstance Instance;
   Instance.setDiagnostics(Diags.get());
@@ -129,7 +139,7 @@ TEST_F(ModuleCacheTest, CachedModuleNewPath) {
  "-Fframeworks",  MCPArg.c_str(), "-working-directory",
  TestDir.c_str(), "test.m"};
   std::shared_ptr Invocation2 =
-  createInvocation(Args2, CIOpts);
+  createInvocationAndEnableFree(Args2, CIOpts);
   ASSERT_TRUE(Invocation2);
   CompilerInstance Instance2(Instance.getPCHContainerOperations(),
  ());
@@ -156,7 +166,7 @@ TEST_F(ModuleCacheTest, CachedModuleNewPathAllowErrors) {
 MCPArg.c_str(), "-working-directory", TestDir.c_str(),
 "test.m"};
   std::shared_ptr Invocation =
-  createInvocation(Args, CIOpts);
+  createInvocationAndEnableFree(Args, CIOpts);
   ASSERT_TRUE(Invocation);
   CompilerInstance Instance;
   Instance.setDiagnostics(Diags.get());
@@ -173,7 +183,7 @@ TEST_F(ModuleCacheTest, CachedModuleNewPathAllowErrors) {
   TestDir.c_str(), "-Xclang",  "-fallow-pcm-with-compiler-errors",
   "test.m"};
   std::shared_ptr Invocation2 =
-  createInvocation(Args2, CIOpts);
+  createInvocationAndEnableFree(Args2, CIOpts);
   ASSERT_TRUE(Invocation2);
   CompilerInstance Instance2(Instance.getPCHContainerOperations(),
  ());
diff --git a/clang/unittests/Serialization/VarDeclConstantInitTest.cpp 
b/clang/unittests/Serialization/VarDeclConstantInitTest.cpp
index 86ae929e7f17e4..7efa1c1d64a964 100644
--- a/clang/unittests/Serialization/VarDeclConstantInitTest.cpp
+++ b/clang/unittests/Serialization/VarDeclConstantInitTest.cpp
@@ -103,6 +103,7 @@ export namespace Fibonacci
   std::shared_ptr Invocation =
   createInvocation(Args, CIOpts);
   ASSERT_TRUE(Invocation);
+  Invocation->getFrontendOpts().DisableFree = false;
 
   CompilerInstance Instance;
   Instance.setDiagnostics(Diags.get());

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-format] Add common attribute macros to Google style (PR #76239)

2023-12-22 Thread Krasimir Georgiev via cfe-commits

https://github.com/krasimirgg approved this pull request.

thank you!

https://github.com/llvm/llvm-project/pull/76239
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-format] Do not break on JS fields like on goto labels (PR #76233)

2023-12-22 Thread Krasimir Georgiev via cfe-commits

https://github.com/krasimirgg approved this pull request.

thank you!

https://github.com/llvm/llvm-project/pull/76233
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] f5af7d2 - Revert "[clang][ExprConstant] fix __builtin_object_size for flexible array members"

2023-05-23 Thread Krasimir Georgiev via cfe-commits

Author: Krasimir Georgiev
Date: 2023-05-23T07:59:38Z
New Revision: f5af7d2d987b0b16d7a641b7aa9086a75d533944

URL: 
https://github.com/llvm/llvm-project/commit/f5af7d2d987b0b16d7a641b7aa9086a75d533944
DIFF: 
https://github.com/llvm/llvm-project/commit/f5af7d2d987b0b16d7a641b7aa9086a75d533944.diff

LOG: Revert "[clang][ExprConstant] fix __builtin_object_size for flexible array 
members"

This reverts commit 57c5c1ab2a188b7962c9de5ac0f95e3c7441940a.

Causes an assertion failure: https://reviews.llvm.org/D150892#4363080

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/AST/ExprConstant.cpp
clang/test/CodeGen/object-size.c

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index a124617fac8b..915c9b0cf101 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -51,11 +51,6 @@ C/C++ Language Potentially Breaking Changes
 
 foo: asm goto ("# %0 %1"::"i"(&)::foo);
 
-- ``__builtin_object_size`` and ``__builtin_dynamic_object_size`` now add the
-  ``sizeof`` the elements specified in designated initializers of flexible
-  array members for structs that contain them. This change is more consistent
-  with the behavior of GCC.
-
 C++ Specific Potentially Breaking Changes
 -
 - Clang won't search for coroutine_traits in std::experimental namespace any 
more.
@@ -429,10 +424,6 @@ Bug Fixes in This Version
   (`#61746 `_).
 - Clang `TextNodeDumper` enabled through `-ast-dump` flag no longer evaluates 
the
   initializer of constexpr `VarDecl` if the declaration has a dependent type.
-- Match GCC's behavior for ``__builtin_object_size`` and
-  ``__builtin_dynamic_object_size`` on structs containing flexible array
-  members.
-  (`#62789 `_).
 
 Bug Fixes to Compiler Builtins
 ^^

diff  --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index f1a30da1ff77..ce3c5257e711 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -11733,14 +11733,7 @@ static bool determineEndOffset(EvalInfo , 
SourceLocation ExprLoc,
   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits ) {
 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
   return false;
-bool Ret = HandleSizeof(Info, ExprLoc, Ty, Result);
-if (Ty->isStructureType() &&
-Ty->getAsStructureType()->getDecl()->hasFlexibleArrayMember()) {
-  const auto *VD =
-  cast(LVal.getLValueBase().get());
-  Result += VD->getFlexibleArrayInitChars(Info.Ctx);
-}
-return Ret;
+return HandleSizeof(Info, ExprLoc, Ty, Result);
   };
 
   // We want to evaluate the size of the entire object. This is a valid 
fallback

diff  --git a/clang/test/CodeGen/object-size.c 
b/clang/test/CodeGen/object-size.c
index ac1551343d6f..157926dd719d 100644
--- a/clang/test/CodeGen/object-size.c
+++ b/clang/test/CodeGen/object-size.c
@@ -525,33 +525,6 @@ void test31(void) {
   gi = OBJECT_SIZE_BUILTIN([9].snd[0], 1);
 }
 
-// CHECK-LABEL: @test32
-static struct DynStructVar D32 = {
-  .fst = {},
-  .snd = { 0, 1, 2, },
-};
-unsigned long test32(void) {
-  // CHECK: ret i64 19
-  return OBJECT_SIZE_BUILTIN(, 1);
-}
-// CHECK-LABEL: @test33
-static struct DynStructVar D33 = {
-  .fst = {},
-  .snd = {},
-};
-unsigned long test33(void) {
-  // CHECK: ret i64 16
-  return OBJECT_SIZE_BUILTIN(, 1);
-}
-// CHECK-LABEL: @test34
-static struct DynStructVar D34 = {
-  .fst = {},
-};
-unsigned long test34(void) {
-  // CHECK: ret i64 16
-  return OBJECT_SIZE_BUILTIN(, 1);
-}
-
 // CHECK-LABEL: @PR30346
 void PR30346(void) {
   struct sa_family_t {};



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] e1f34b7 - clang-format: [JS] terminate import sorting on `export type X = Y`

2023-05-15 Thread Krasimir Georgiev via cfe-commits

Author: Jan Kuhle
Date: 2023-05-15T15:37:18+02:00
New Revision: e1f34b735b669c5978bfdead874ee59d33f99eb0

URL: 
https://github.com/llvm/llvm-project/commit/e1f34b735b669c5978bfdead874ee59d33f99eb0
DIFF: 
https://github.com/llvm/llvm-project/commit/e1f34b735b669c5978bfdead874ee59d33f99eb0.diff

LOG: clang-format: [JS] terminate import sorting on `export type X = Y`

Contributed by @jankuehle!

https://reviews.llvm.org/D150116 introduced a bug. `export type X = Y` was 
considered an export declaration and took part in import sorting. This is not 
correct. With this change `export type X = Y` properly terminates import 
sorting.

Reviewed By: krasimir

Differential Revision: https://reviews.llvm.org/D150563

Added: 


Modified: 
clang/lib/Format/SortJavaScriptImports.cpp
clang/unittests/Format/SortImportsTestJS.cpp

Removed: 




diff  --git a/clang/lib/Format/SortJavaScriptImports.cpp 
b/clang/lib/Format/SortJavaScriptImports.cpp
index af2d3400c970d..e24fe051a26ce 100644
--- a/clang/lib/Format/SortJavaScriptImports.cpp
+++ b/clang/lib/Format/SortJavaScriptImports.cpp
@@ -517,7 +517,7 @@ class JavaScriptImportSorter : public TokenAnalyzer {
 }
 
 // eat a potential "import X, " prefix.
-if (Current->is(tok::identifier)) {
+if (!Reference.IsExport && Current->is(tok::identifier)) {
   Reference.DefaultImport = Current->TokenText;
   nextToken();
   if (Current->is(Keywords.kw_from))

diff  --git a/clang/unittests/Format/SortImportsTestJS.cpp 
b/clang/unittests/Format/SortImportsTestJS.cpp
index 9d779cd988d0c..2778d6efcdf9a 100644
--- a/clang/unittests/Format/SortImportsTestJS.cpp
+++ b/clang/unittests/Format/SortImportsTestJS.cpp
@@ -503,6 +503,15 @@ TEST_F(SortImportsTestJS, ImportExportType) {
   verifySort("export {A, type B} from 'foo';\n",
  "export {A} from 'foo';\n"
  "export   {type B} from 'foo';");
+
+  // `export type X = Y;` should terminate import sorting. The following export
+  // statements should therefore not merge.
+  verifySort("export type A = B;\n"
+ "export {X};\n"
+ "export {Y};\n",
+ "export type A = B;\n"
+ "export {X};\n"
+ "export {Y};\n");
 }
 
 } // end namespace



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 34b422b - clang-format: [JS] support import/export type

2023-05-10 Thread Krasimir Georgiev via cfe-commits

Author: Jan Kuhle
Date: 2023-05-10T15:27:03+02:00
New Revision: 34b422bafbd934ee3c644fd7a8f0b6803976c818

URL: 
https://github.com/llvm/llvm-project/commit/34b422bafbd934ee3c644fd7a8f0b6803976c818
DIFF: 
https://github.com/llvm/llvm-project/commit/34b422bafbd934ee3c644fd7a8f0b6803976c818.diff

LOG: clang-format: [JS] support import/export type

Contributed by @jankuehle!

Users can choose to only import/export the type of the symbol (not value nor 
namespace) by adding a `type` keyword, e.g.:

```
import type {x} from 'y';
import {type x} from 'y';
export type {x};
export {type x};
```

Previously, this was not handled and would:
- Terminate import sorting
- Remove the space before the curly bracket in `export type {`

With this change, both formatting and import sorting work as expected.

Reviewed By: MyDeveloperDay, krasimir

Differential Revision: https://reviews.llvm.org/D150116

Added: 


Modified: 
clang/lib/Format/SortJavaScriptImports.cpp
clang/lib/Format/UnwrappedLineParser.cpp
clang/unittests/Format/FormatTestJS.cpp
clang/unittests/Format/SortImportsTestJS.cpp

Removed: 




diff  --git a/clang/lib/Format/SortJavaScriptImports.cpp 
b/clang/lib/Format/SortJavaScriptImports.cpp
index ce83ddea3e076..af2d3400c970d 100644
--- a/clang/lib/Format/SortJavaScriptImports.cpp
+++ b/clang/lib/Format/SortJavaScriptImports.cpp
@@ -72,6 +72,7 @@ struct JsImportedSymbol {
 struct JsModuleReference {
   bool FormattingOff = false;
   bool IsExport = false;
+  bool IsTypeOnly = false;
   // Module references are sorted into these categories, in order.
   enum ReferenceCategory {
 SIDE_EFFECT, // "import 'something';"
@@ -306,6 +307,7 @@ class JavaScriptImportSorter : public TokenAnalyzer {
   if (Reference->Category == JsModuleReference::SIDE_EFFECT ||
   PreviousReference->Category == JsModuleReference::SIDE_EFFECT ||
   Reference->IsExport != PreviousReference->IsExport ||
+  Reference->IsTypeOnly != PreviousReference->IsTypeOnly ||
   !PreviousReference->Prefix.empty() || !Reference->Prefix.empty() ||
   !PreviousReference->DefaultImport.empty() ||
   !Reference->DefaultImport.empty() || Reference->Symbols.empty() ||
@@ -488,6 +490,11 @@ class JavaScriptImportSorter : public TokenAnalyzer {
   bool parseStarBinding(const AdditionalKeywords ,
 JsModuleReference ) {
 // * as prefix from '...';
+if (Current->is(Keywords.kw_type) && Current->Next &&
+Current->Next->is(tok::star)) {
+  Reference.IsTypeOnly = true;
+  nextToken();
+}
 if (Current->isNot(tok::star))
   return false;
 nextToken();
@@ -503,6 +510,12 @@ class JavaScriptImportSorter : public TokenAnalyzer {
 
   bool parseNamedBindings(const AdditionalKeywords ,
   JsModuleReference ) {
+if (Current->is(Keywords.kw_type) && Current->Next &&
+Current->Next->isOneOf(tok::identifier, tok::l_brace)) {
+  Reference.IsTypeOnly = true;
+  nextToken();
+}
+
 // eat a potential "import X, " prefix.
 if (Current->is(tok::identifier)) {
   Reference.DefaultImport = Current->TokenText;
@@ -535,14 +548,19 @@ class JavaScriptImportSorter : public TokenAnalyzer {
   nextToken();
   if (Current->is(tok::r_brace))
 break;
-  if (!Current->isOneOf(tok::identifier, tok::kw_default))
+  bool isTypeOnly =
+  Current->is(Keywords.kw_type) && Current->Next &&
+  Current->Next->isOneOf(tok::identifier, tok::kw_default);
+  if (!isTypeOnly && !Current->isOneOf(tok::identifier, tok::kw_default))
 return false;
 
   JsImportedSymbol Symbol;
-  Symbol.Symbol = Current->TokenText;
   // Make sure to include any preceding comments.
   Symbol.Range.setBegin(
   Current->getPreviousNonComment()->Next->WhitespaceRange.getBegin());
+  if (isTypeOnly)
+nextToken();
+  Symbol.Symbol = Current->TokenText;
   nextToken();
 
   if (Current->is(Keywords.kw_as)) {

diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 2e5bdf96deb88..64035b0976f55 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -4068,7 +4068,9 @@ void 
UnwrappedLineParser::parseJavaScriptEs6ImportExport() {
   // parsing the structural element, i.e. the declaration or expression for
   // `export default`.
   if (!IsImport && !FormatTok->isOneOf(tok::l_brace, tok::star) &&
-  !FormatTok->isStringLiteral()) {
+  !FormatTok->isStringLiteral() &&
+  !(FormatTok->is(Keywords.kw_type) &&
+Tokens->peekNextToken()->isOneOf(tok::l_brace, tok::star))) {
 return;
   }
 

diff  --git a/clang/unittests/Format/FormatTestJS.cpp 
b/clang/unittests/Format/FormatTestJS.cpp
index 6f07d8b084f56..ce81bd5d2f044 100644
--- 

[clang] 1689a5d - [clang] fix an unused variable warning after 9d0b55f0e4ca55d04ee8abfdf021913ea3c30082

2023-04-13 Thread Krasimir Georgiev via cfe-commits

Author: Krasimir Georgiev
Date: 2023-04-13T10:03:37Z
New Revision: 1689a5d756f81d615bcfca8de2631b0ccc8a3917

URL: 
https://github.com/llvm/llvm-project/commit/1689a5d756f81d615bcfca8de2631b0ccc8a3917
DIFF: 
https://github.com/llvm/llvm-project/commit/1689a5d756f81d615bcfca8de2631b0ccc8a3917.diff

LOG: [clang] fix an unused variable warning after 
9d0b55f0e4ca55d04ee8abfdf021913ea3c30082

Added: 


Modified: 
clang/unittests/AST/ASTImporterTest.cpp

Removed: 




diff  --git a/clang/unittests/AST/ASTImporterTest.cpp 
b/clang/unittests/AST/ASTImporterTest.cpp
index b90a18d53966..532fef6df5e3 100644
--- a/clang/unittests/AST/ASTImporterTest.cpp
+++ b/clang/unittests/AST/ASTImporterTest.cpp
@@ -8624,7 +8624,6 @@ TEST_P(ASTImporterOptionSpecificTestBase,
 
   auto X = 0 ? (RPX1){} : (RPY1){};
   )";
-  Decl *ToTU = getToTuDecl("", Lang_CXX11);
   Decl *FromTU = getTuDecl(Code, Lang_CXX11);
 
   auto *FromX =



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 1e07091 - Revert "[Modules] Remove unnecessary check when generating name lookup table in ASTWriter"

2023-03-10 Thread Krasimir Georgiev via cfe-commits

Author: Krasimir Georgiev
Date: 2023-03-10T14:14:55+01:00
New Revision: 1e0709167f5edd330889f51bb203c458bdb5e359

URL: 
https://github.com/llvm/llvm-project/commit/1e0709167f5edd330889f51bb203c458bdb5e359
DIFF: 
https://github.com/llvm/llvm-project/commit/1e0709167f5edd330889f51bb203c458bdb5e359.diff

LOG: Revert "[Modules] Remove unnecessary check when generating name lookup 
table in ASTWriter"

This reverts commit db987b9589be1eb604fcb74c85b410469e31485f.

We're seeing failures in modules-enabled builds from within stdlib after
this commit. Errors look like:

In module '...stl_cc_library':
...optional:560:38: error: 'std::__optional_copy_assign_base::__optional_copy_assign_base' from module '...optional' is not
present in definition of 'std::__optional_copy_assign_base' in module '...optional'
using __optional_move_base<_Tp>::__optional_move_base;

In module '...stl_cc_library':
...optional:771:11: error: no matching constructor for initialization of 
'__optional_move_assign_base'
: __base(in_place, _VSTD::forward<_Up>(__v)) {}
  ^  ~~
llvm-project/clang/include/clang/Basic/CodeGenOptions.h:448:57: note: in 
instantiation of function template specialization 'std::optional::optional' requested here
  std::optional DiagnosticsHotnessThreshold = 0;

I don't have a self-contained reproducer at this point. I'm hoping that
we may be able to share more information about these issues later, if
necessary.

Added: 


Modified: 
clang/include/clang/Serialization/ASTWriter.h
clang/lib/Serialization/ASTWriter.cpp

Removed: 
clang/test/Modules/pr61065.cppm



diff  --git a/clang/include/clang/Serialization/ASTWriter.h 
b/clang/include/clang/Serialization/ASTWriter.h
index d31fa38b93825..09ee1744e8945 100644
--- a/clang/include/clang/Serialization/ASTWriter.h
+++ b/clang/include/clang/Serialization/ASTWriter.h
@@ -514,6 +514,7 @@ class ASTWriter : public ASTDeserializationListener,
   void WriteTypeAbbrevs();
   void WriteType(QualType T);
 
+  bool isLookupResultExternal(StoredDeclsList , DeclContext *DC);
   bool isLookupResultEntirelyExternal(StoredDeclsList , DeclContext 
*DC);
 
   void GenerateNameLookupTable(const DeclContext *DC,

diff  --git a/clang/lib/Serialization/ASTWriter.cpp 
b/clang/lib/Serialization/ASTWriter.cpp
index 5f8f5d38932a5..c1afdeb6007db 100644
--- a/clang/lib/Serialization/ASTWriter.cpp
+++ b/clang/lib/Serialization/ASTWriter.cpp
@@ -3849,6 +3849,12 @@ class ASTDeclContextNameLookupTrait {
 
 } // namespace
 
+bool ASTWriter::isLookupResultExternal(StoredDeclsList ,
+   DeclContext *DC) {
+  return Result.hasExternalDecls() &&
+ DC->hasNeedToReconcileExternalVisibleStorage();
+}
+
 bool ASTWriter::isLookupResultEntirelyExternal(StoredDeclsList ,
DeclContext *DC) {
   for (auto *D : Result.getLookupResult())
@@ -3891,7 +3897,8 @@ ASTWriter::GenerateNameLookupTable(const DeclContext 
*ConstDC,
 // don't need to write an entry for the name at all. If we can't
 // write out a lookup set without performing more deserialization,
 // just skip this entry.
-if (isLookupResultEntirelyExternal(Result, DC))
+if (isLookupResultExternal(Result, DC) &&
+isLookupResultEntirelyExternal(Result, DC))
   continue;
 
 // We also skip empty results. If any of the results could be external and

diff  --git a/clang/test/Modules/pr61065.cppm b/clang/test/Modules/pr61065.cppm
deleted file mode 100644
index 44fa3679974ad..0
--- a/clang/test/Modules/pr61065.cppm
+++ /dev/null
@@ -1,55 +0,0 @@
-// From https://github.com/llvm/llvm-project/issues/61065
-// RUN: rm -rf %t
-// RUN: mkdir -p %t
-// RUN: split-file %s %t
-//
-// RUN: %clang_cc1 -std=c++20 %t/a.cppm -emit-module-interface -o %t/a.pcm
-// RUN: %clang_cc1 -std=c++20 %t/b.cppm -emit-module-interface -o %t/b.pcm \
-// RUN: -fprebuilt-module-path=%t
-// RUN: %clang_cc1 -std=c++20 %t/c.cppm -emit-module-interface -o %t/c.pcm \
-// RUN: -fprebuilt-module-path=%t
-// RUN: %clang_cc1 -std=c++20 %t/d.cpp -fsyntax-only -verify 
-fprebuilt-module-path=%t
-
-//--- a.cppm
-export module a;
-
-struct base {
-   base(int) {}
-};
-
-export struct a : base {
-   using base::base;
-};
-
-//--- b.cppm
-export module b;
-
-import a;
-
-a b() {
-   return a(1);
-}
-
-//--- c.cppm
-export module c;
-
-import a;
-import b;
-
-struct noncopyable {
-   noncopyable(noncopyable const &) = delete;
-noncopyable() = default;
-};
-
-export struct c {
-   noncopyable c0;
-   a c1 = 43;
-c() = default;
-};
-
-//--- d.cpp
-// expected-no-diagnostics
-import c;
-void d() {
-c _;
-}



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] caf393d - Fix format for `case` in .proto files

2023-01-16 Thread Krasimir Georgiev via cfe-commits

Author: Matt Kulukundis
Date: 2023-01-16T17:43:50Z
New Revision: caf393da1823d50852f51604b3793e8f4a23c140

URL: 
https://github.com/llvm/llvm-project/commit/caf393da1823d50852f51604b3793e8f4a23c140
DIFF: 
https://github.com/llvm/llvm-project/commit/caf393da1823d50852f51604b3793e8f4a23c140.diff

LOG: Fix format for `case` in .proto files

Fix format for `case` in .proto files

Reviewed By: krasimir, echristo

Differential Revision: https://reviews.llvm.org/D141547

Added: 


Modified: 
clang/lib/Format/UnwrappedLineParser.cpp
clang/unittests/Format/FormatTestProto.cpp

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index c97ecc7821209..effb0ecb368bb 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -590,8 +590,9 @@ bool UnwrappedLineParser::parseLevel(const FormatToken 
*OpeningBrace,
   [[fallthrough]];
 }
 case tok::kw_case:
-  if (Style.isVerilog() ||
+  if (Style.isProto() || Style.isVerilog() ||
   (Style.isJavaScript() && Line->MustBeDeclaration)) {
+// Proto: there are no switch/case statements
 // Verilog: Case labels don't have this word. We handle case
 // labels including default in TokenAnnotator.
 // JavaScript: A 'case: string' style field declaration.
@@ -1620,7 +1621,11 @@ void UnwrappedLineParser::parseStructuralElement(
 // e.g. "default void f() {}" in a Java interface.
 break;
   case tok::kw_case:
-// In Verilog switch is called case.
+// Proto: there are no switch/case statements.
+if (Style.isProto()) {
+  nextToken();
+  return;
+}
 if (Style.isVerilog()) {
   parseBlock();
   addUnwrappedLine();
@@ -2100,6 +2105,11 @@ void UnwrappedLineParser::parseStructuralElement(
   parseNew();
   break;
 case tok::kw_case:
+  // Proto: there are no switch/case statements.
+  if (Style.isProto()) {
+nextToken();
+return;
+  }
   // In Verilog switch is called case.
   if (Style.isVerilog()) {
 parseBlock();

diff  --git a/clang/unittests/Format/FormatTestProto.cpp 
b/clang/unittests/Format/FormatTestProto.cpp
index 1ff7c22a6df78..5de40b6eae597 100644
--- a/clang/unittests/Format/FormatTestProto.cpp
+++ b/clang/unittests/Format/FormatTestProto.cpp
@@ -113,6 +113,13 @@ TEST_F(FormatTestProto, EnumAsFieldName) {
"}");
 }
 
+TEST_F(FormatTestProto, CaseAsFieldName) {
+  verifyFormat("message SomeMessage {\n"
+   "  required string case = 1;\n"
+   "  repeated int32 fizz = 2;\n"
+   "}");
+}
+
 TEST_F(FormatTestProto, UnderstandsReturns) {
   verifyFormat("rpc Search(SearchRequest) returns (SearchResponse);");
 }



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 922c889 - Revert "Revert "[clang-format] Add an option for breaking after C++11 attributes""

2023-01-11 Thread Krasimir Georgiev via cfe-commits

Author: Krasimir Georgiev
Date: 2023-01-11T11:30:30Z
New Revision: 922c8891d9916fa094147c5c793291f97a83c84c

URL: 
https://github.com/llvm/llvm-project/commit/922c8891d9916fa094147c5c793291f97a83c84c
DIFF: 
https://github.com/llvm/llvm-project/commit/922c8891d9916fa094147c5c793291f97a83c84c.diff

LOG: Revert "Revert "[clang-format] Add an option for breaking after C++11 
attributes""

This reverts commit 879bfe6a979295f834b76df66b19a203b93eed0f.

owenpan@ pointed out on https://reviews.llvm.org/D140956 that this
actually makes the formatting more consistent, so it's not a regression.

Added: 


Modified: 
clang/docs/ClangFormatStyleOptions.rst
clang/docs/ReleaseNotes.rst
clang/include/clang/Format/Format.h
clang/lib/Format/ContinuationIndenter.cpp
clang/lib/Format/Format.cpp
clang/lib/Format/FormatToken.h
clang/lib/Format/TokenAnnotator.cpp
clang/lib/Format/TokenAnnotator.h
clang/unittests/Format/ConfigParseTest.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index fd2a9438a3327..05eca35aa9714 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -1762,6 +1762,41 @@ the configuration (without a prefix: ``Auto``).
}
 
 
+**BreakAfterAttributes** (``AttributeBreakingStyle``) 
:versionbadge:`clang-format 16`
+  Break after a group of C++11 attributes before a function
+  declaration/definition name.
+
+  Possible values:
+
+  * ``ABS_Always`` (in configuration: ``Always``)
+Always break after attributes.
+
+.. code-block:: c++
+
+  [[nodiscard]]
+  inline int f();
+  [[gnu::const]] [[nodiscard]]
+  int g();
+
+  * ``ABS_Leave`` (in configuration: ``Leave``)
+Leave the line breaking after attributes as is.
+
+.. code-block:: c++
+
+  [[nodiscard]] inline int f();
+  [[gnu::const]] [[nodiscard]]
+  int g();
+
+  * ``ABS_Never`` (in configuration: ``Never``)
+Never break after attributes.
+
+.. code-block:: c++
+
+  [[nodiscard]] inline int f();
+  [[gnu::const]] [[nodiscard]] int g();
+
+
+
 **BreakAfterJavaFieldAnnotations** (``Boolean``) :versionbadge:`clang-format 
3.8`
   Break after each annotation on a field in Java files.
 

diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 235684c1f9b87..3d7b07f88101d 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -891,6 +891,8 @@ clang-format
   To match the default behavior of clang-format 15, use the ``Keyword`` value.
 - Add ``IntegerLiteralSeparator`` option for fixing integer literal separators
   in C++, C#, Java, and JavaScript.
+- Add ``BreakAfterAttributes`` option for breaking after a group of C++11
+  attributes before a function declaration/definition name.
 - Add ``InsertNewlineAtEOF`` option for inserting a newline at EOF if missing.
 
 clang-extdef-mapping

diff  --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 5d5a044158dfb..3a90c1fe5be99 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -1221,6 +1221,36 @@ struct FormatStyle {
   /// \version 3.8
   BraceWrappingFlags BraceWrapping;
 
+  /// Different ways to break after attributes.
+  enum AttributeBreakingStyle : int8_t {
+/// Always break after attributes.
+/// \code
+///   [[nodiscard]]
+///   inline int f();
+///   [[gnu::const]] [[nodiscard]]
+///   int g();
+/// \endcode
+ABS_Always,
+/// Leave the line breaking after attributes as is.
+/// \code
+///   [[nodiscard]] inline int f();
+///   [[gnu::const]] [[nodiscard]]
+///   int g();
+/// \endcode
+ABS_Leave,
+/// Never break after attributes.
+/// \code
+///   [[nodiscard]] inline int f();
+///   [[gnu::const]] [[nodiscard]] int g();
+/// \endcode
+ABS_Never,
+  };
+
+  /// Break after a group of C++11 attributes before a function
+  /// declaration/definition name.
+  /// \version 16
+  AttributeBreakingStyle BreakAfterAttributes;
+
   /// If ``true``, clang-format will always break after a Json array `[`
   /// otherwise it will scan until the closing `]` to determine if it should 
add
   /// newlines between elements (prettier compatible).
@@ -4097,6 +4127,7 @@ struct FormatStyle {
BinPackArguments == R.BinPackArguments &&
BinPackParameters == R.BinPackParameters &&
BitFieldColonSpacing == R.BitFieldColonSpacing &&
+   BreakAfterAttributes == R.BreakAfterAttributes &&
BreakAfterJavaFieldAnnotations == R.BreakAfterJavaFieldAnnotations 
&&
BreakArrays == R.BreakArrays &&
BreakBeforeBinaryOperators == R.BreakBeforeBinaryOperators &&

diff  --git 

[clang] 879bfe6 - Revert "[clang-format] Add an option for breaking after C++11 attributes"

2023-01-10 Thread Krasimir Georgiev via cfe-commits

Author: Krasimir Georgiev
Date: 2023-01-10T09:23:44Z
New Revision: 879bfe6a979295f834b76df66b19a203b93eed0f

URL: 
https://github.com/llvm/llvm-project/commit/879bfe6a979295f834b76df66b19a203b93eed0f
DIFF: 
https://github.com/llvm/llvm-project/commit/879bfe6a979295f834b76df66b19a203b93eed0f.diff

LOG: Revert "[clang-format] Add an option for breaking after C++11 attributes"

This reverts commit a28f0747c2f3728bd8a6f64f7c8ba80b4e0cda9f.

It appears that this regresses some function definitions, added an
example as a comment over at https://reviews.llvm.org/D140956.

Added: 


Modified: 
clang/docs/ClangFormatStyleOptions.rst
clang/docs/ReleaseNotes.rst
clang/include/clang/Format/Format.h
clang/lib/Format/ContinuationIndenter.cpp
clang/lib/Format/Format.cpp
clang/lib/Format/FormatToken.h
clang/lib/Format/TokenAnnotator.cpp
clang/lib/Format/TokenAnnotator.h
clang/unittests/Format/ConfigParseTest.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 4134d5a387d2d..23f5786723f6d 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -1762,41 +1762,6 @@ the configuration (without a prefix: ``Auto``).
}
 
 
-**BreakAfterAttributes** (``AttributeBreakingStyle``) 
:versionbadge:`clang-format 16`
-  Break after a group of C++11 attributes before a function
-  declaration/definition name.
-
-  Possible values:
-
-  * ``ABS_Always`` (in configuration: ``Always``)
-Always break after attributes.
-
-.. code-block:: c++
-
-  [[nodiscard]]
-  inline int f();
-  [[gnu::const]] [[nodiscard]]
-  int g();
-
-  * ``ABS_Leave`` (in configuration: ``Leave``)
-Leave the line breaking after attributes as is.
-
-.. code-block:: c++
-
-  [[nodiscard]] inline int f();
-  [[gnu::const]] [[nodiscard]]
-  int g();
-
-  * ``ABS_Never`` (in configuration: ``Never``)
-Never break after attributes.
-
-.. code-block:: c++
-
-  [[nodiscard]] inline int f();
-  [[gnu::const]] [[nodiscard]] int g();
-
-
-
 **BreakAfterJavaFieldAnnotations** (``Boolean``) :versionbadge:`clang-format 
3.8`
   Break after each annotation on a field in Java files.
 

diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 8718deab35bf2..927c85249b729 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -889,8 +889,6 @@ clang-format
   To match the default behavior of clang-format 15, use the ``Keyword`` value.
 - Add ``IntegerLiteralSeparator`` option for fixing integer literal separators
   in C++, C#, Java, and JavaScript.
-- Add ``BreakAfterAttributes`` option for breaking after a group of C++11
-  attributes before a function declaration/definition name.
 - Add ``InsertNewlineAtEOF`` option for inserting a newline at EOF if missing.
 
 clang-extdef-mapping

diff  --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 6e5d3a163ec32..3a7a183d139f0 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -1221,36 +1221,6 @@ struct FormatStyle {
   /// \version 3.8
   BraceWrappingFlags BraceWrapping;
 
-  /// Different ways to break after attributes.
-  enum AttributeBreakingStyle : int8_t {
-/// Always break after attributes.
-/// \code
-///   [[nodiscard]]
-///   inline int f();
-///   [[gnu::const]] [[nodiscard]]
-///   int g();
-/// \endcode
-ABS_Always,
-/// Leave the line breaking after attributes as is.
-/// \code
-///   [[nodiscard]] inline int f();
-///   [[gnu::const]] [[nodiscard]]
-///   int g();
-/// \endcode
-ABS_Leave,
-/// Never break after attributes.
-/// \code
-///   [[nodiscard]] inline int f();
-///   [[gnu::const]] [[nodiscard]] int g();
-/// \endcode
-ABS_Never,
-  };
-
-  /// Break after a group of C++11 attributes before a function
-  /// declaration/definition name.
-  /// \version 16
-  AttributeBreakingStyle BreakAfterAttributes;
-
   /// If ``true``, clang-format will always break after a Json array `[`
   /// otherwise it will scan until the closing `]` to determine if it should 
add
   /// newlines between elements (prettier compatible).
@@ -4113,7 +4083,6 @@ struct FormatStyle {
BinPackArguments == R.BinPackArguments &&
BinPackParameters == R.BinPackParameters &&
BitFieldColonSpacing == R.BitFieldColonSpacing &&
-   BreakAfterAttributes == R.BreakAfterAttributes &&
BreakAfterJavaFieldAnnotations == R.BreakAfterJavaFieldAnnotations 
&&
BreakArrays == R.BreakArrays &&
BreakBeforeBinaryOperators == R.BreakBeforeBinaryOperators &&

diff  --git a/clang/lib/Format/ContinuationIndenter.cpp 

[clang] f86cdb4 - [clang][dataflow] Remove unused lambda capture

2022-12-16 Thread Krasimir Georgiev via cfe-commits

Author: Dani Ferreira Franco Moura
Date: 2022-12-16T15:39:31+01:00
New Revision: f86cdb4853618603b8889dfeb932fd4ef8efd010

URL: 
https://github.com/llvm/llvm-project/commit/f86cdb4853618603b8889dfeb932fd4ef8efd010
DIFF: 
https://github.com/llvm/llvm-project/commit/f86cdb4853618603b8889dfeb932fd4ef8efd010.diff

LOG: [clang][dataflow] Remove unused lambda capture

Reviewed By: krasimir

Differential Revision: https://reviews.llvm.org/D140211

Added: 


Modified: 
clang/lib/Sema/SemaExpr.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index ccb1e3e21cae..94f52004cf6c 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -9069,7 +9069,7 @@ static QualType computeConditionalNullability(QualType 
ResTy, bool IsBin,
   if (!ResTy->isAnyPointerType())
 return ResTy;
 
-  auto GetNullability = [](QualType Ty) {
+  auto GetNullability = [](QualType Ty) {
 Optional Kind = Ty->getNullability();
 if (Kind) {
   // For our purposes, treat _Nullable_result as _Nullable.



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 231992d - [clang] silence unused variable warning

2022-12-16 Thread Krasimir Georgiev via cfe-commits

Author: Krasimir Georgiev
Date: 2022-12-16T11:22:46Z
New Revision: 231992d9b88fe4e0b4aa0f55ed64d7ba88b231ce

URL: 
https://github.com/llvm/llvm-project/commit/231992d9b88fe4e0b4aa0f55ed64d7ba88b231ce
DIFF: 
https://github.com/llvm/llvm-project/commit/231992d9b88fe4e0b4aa0f55ed64d7ba88b231ce.diff

LOG: [clang] silence unused variable warning

No functional changes intended.

Added: 


Modified: 
clang/lib/Lex/Lexer.cpp

Removed: 




diff  --git a/clang/lib/Lex/Lexer.cpp b/clang/lib/Lex/Lexer.cpp
index d1af455fbb91..2f21f7b069cf 100644
--- a/clang/lib/Lex/Lexer.cpp
+++ b/clang/lib/Lex/Lexer.cpp
@@ -1548,6 +1548,8 @@ static void 
diagnoseExtensionInIdentifier(DiagnosticsEngine , uint32_t C,
   static const llvm::sys::UnicodeCharSet MathContinueChars(
   MathematicalNotationProfileIDContinueRanges);
 
+  (void)MathStartChars;
+  (void)MathContinueChars;
   assert((MathStartChars.contains(C) || MathContinueChars.contains(C)) &&
  "Unexpected mathematical notation codepoint");
   Diags.Report(Range.getBegin(), diag::ext_mathematical_notation)



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 339a768 - Revert "Implement CWG2631"

2022-12-14 Thread Krasimir Georgiev via cfe-commits

Author: Krasimir Georgiev
Date: 2022-12-14T09:10:22Z
New Revision: 339a7687e1c036a5f91c9d5391523b93e2e76cd3

URL: 
https://github.com/llvm/llvm-project/commit/339a7687e1c036a5f91c9d5391523b93e2e76cd3
DIFF: 
https://github.com/llvm/llvm-project/commit/339a7687e1c036a5f91c9d5391523b93e2e76cd3.diff

LOG: Revert "Implement CWG2631"

This reverts commit f1f1b60c7ba607e9ffe3bc012161d43ef95ac773.

Temporary revert, possibly triggers a new assertion failure on
QualType::getCommonPtr.
We're working on a reproducer, to follow-up on
https://reviews.llvm.org/D136554.

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/AST/ExprCXX.h
clang/include/clang/AST/Stmt.h
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/include/clang/Sema/Sema.h
clang/lib/AST/ASTImporter.cpp
clang/lib/AST/Decl.cpp
clang/lib/AST/ExprCXX.cpp
clang/lib/Parse/ParseCXXInlineMethods.cpp
clang/lib/Parse/ParseDeclCXX.cpp
clang/lib/Sema/SemaDeclCXX.cpp
clang/lib/Sema/SemaExpr.cpp
clang/lib/Sema/SemaTemplateInstantiate.cpp
clang/lib/Sema/TreeTransform.h
clang/lib/Sema/UsedDeclVisitor.h
clang/lib/Serialization/ASTReaderStmt.cpp
clang/lib/Serialization/ASTWriterStmt.cpp
clang/test/CXX/class/class.local/p1-0x.cpp
clang/test/CXX/drs/dr26xx.cpp
clang/test/CodeGenCXX/builtin-source-location.cpp
clang/test/SemaCXX/cxx11-default-member-initializers.cpp
clang/test/SemaCXX/source_location.cpp
clang/www/cxx_dr_status.html

Removed: 
clang/test/CodeGenCXX/default-arguments-with-immediate.cpp
clang/test/CodeGenCXX/meminit-initializers-odr.cpp
clang/test/PCH/default-argument-with-immediate-calls.cpp
clang/test/SemaCXX/cxx2a-consteval-default-params.cpp



diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 73f2962ff2fc7..cad59b0ce5def 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -645,11 +645,6 @@ C++ Language Changes in Clang
 - Implemented DR2358 allowing init captures in lambdas in default arguments.
 - implemented `DR2654 `_ which undeprecates
   all compound assignements operations on volatile qualified variables.
-- Implemented DR2631. Invalid ``consteval`` calls in default arguments and 
default
-  member initializers are diagnosed when and if the default is used.
-  This Fixes `Issue 56379 `_
-  and changes the value of ``std::source_location::current()``
-  used in default parameters calls compared to previous versions of Clang.
 
 C++20 Feature Support
 ^

diff  --git a/clang/include/clang/AST/ExprCXX.h 
b/clang/include/clang/AST/ExprCXX.h
index e99ebe6126824..c2f6751d62ede 100644
--- a/clang/include/clang/AST/ExprCXX.h
+++ b/clang/include/clang/AST/ExprCXX.h
@@ -1244,12 +1244,8 @@ class CXXThrowExpr : public Expr {
 /// This wraps up a function call argument that was created from the
 /// corresponding parameter's default argument, when the call did not
 /// explicitly supply arguments for all of the parameters.
-class CXXDefaultArgExpr final
-: public Expr,
-  private llvm::TrailingObjects {
+class CXXDefaultArgExpr final : public Expr {
   friend class ASTStmtReader;
-  friend class ASTReader;
-  friend TrailingObjects;
 
   /// The parameter whose default is being used.
   ParmVarDecl *Param;
@@ -1258,7 +1254,7 @@ class CXXDefaultArgExpr final
   DeclContext *UsedContext;
 
   CXXDefaultArgExpr(StmtClass SC, SourceLocation Loc, ParmVarDecl *Param,
-Expr *RewrittenExpr, DeclContext *UsedContext)
+DeclContext *UsedContext)
   : Expr(SC,
  Param->hasUnparsedDefaultArg()
  ? Param->getType().getNonReferenceType()
@@ -1267,58 +1263,28 @@ class CXXDefaultArgExpr final
  Param->getDefaultArg()->getObjectKind()),
 Param(Param), UsedContext(UsedContext) {
 CXXDefaultArgExprBits.Loc = Loc;
-CXXDefaultArgExprBits.HasRewrittenInit = RewrittenExpr != nullptr;
-if (RewrittenExpr)
-  *getTrailingObjects() = RewrittenExpr;
 setDependence(computeDependence(this));
   }
 
-  CXXDefaultArgExpr(EmptyShell Empty, bool HasRewrittenInit)
-  : Expr(CXXDefaultArgExprClass, Empty) {
-CXXDefaultArgExprBits.HasRewrittenInit = HasRewrittenInit;
-  }
-
-  size_t numTrailingObjects() const {
-return CXXDefaultArgExprBits.HasRewrittenInit;
-  }
-
 public:
-  static CXXDefaultArgExpr *CreateEmpty(const ASTContext ,
-bool HasRewrittenInit);
+  CXXDefaultArgExpr(EmptyShell Empty) : Expr(CXXDefaultArgExprClass, Empty) {}
 
   // \p Param is the parameter whose default argument is used by this
   // expression.
   static CXXDefaultArgExpr *Create(const ASTContext , SourceLocation Loc,
-   ParmVarDecl *Param, Expr 

[clang] 8dd2ef2 - [clang-format] distinguish multiplication after brace-init from pointer

2022-07-15 Thread Krasimir Georgiev via cfe-commits

Author: Krasimir Georgiev
Date: 2022-07-15T11:45:12+02:00
New Revision: 8dd2ef2130852e406dab6097b1feb248bf16ce91

URL: 
https://github.com/llvm/llvm-project/commit/8dd2ef2130852e406dab6097b1feb248bf16ce91
DIFF: 
https://github.com/llvm/llvm-project/commit/8dd2ef2130852e406dab6097b1feb248bf16ce91.diff

LOG: [clang-format] distinguish multiplication after brace-init from pointer

After 
https://github.com/llvm/llvm-project/commit/b646f0955574c6ad4c156c9db522e46f597cfda9,
the added regression test started being formatted as-if the
multiplication `*` was a pointer. This adapts the heuristic to
distinguish between these two cases.

Reviewed By: jackhong12, curdeius, HazardyKnusperkeks, owenpan

Differential Revision: https://reviews.llvm.org/D129771

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTest.cpp
clang/unittests/Format/TokenAnnotatorTest.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 98c012994f45..e0dc7a7f05c9 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2317,7 +2317,15 @@ class AnnotatingParser {
 // After right braces, star tokens are likely to be pointers to struct,
 // union, or class.
 //   struct {} *ptr;
-if (PrevToken->is(tok::r_brace) && Tok.is(tok::star))
+// This by itself is not sufficient to distinguish from multiplication
+// following a brace-initialized expression, as in:
+// int i = int{42} * 2;
+// In the struct case, the part of the struct declaration until the `{` and
+// the `}` are put on separate unwrapped lines; in the brace-initialized
+// case, the matching `{` is on the same unwrapped line, so check for the
+// presence of the matching brace to distinguish between those.
+if (PrevToken->is(tok::r_brace) && Tok.is(tok::star) &&
+!PrevToken->MatchingParen)
   return TT_PointerOrReference;
 
 // For "} &&"

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index ba07584d661a..08cfdbe2cc7a 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -10458,6 +10458,9 @@ TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
   verifyFormat("class {\n"
"}* ptr;",
Style);
+  // Don't confuse a multiplication after a brace-initialized expression with
+  // a class pointer.
+  verifyFormat("int i = int{42} * 34;", Style);
   verifyFormat("struct {\n"
"}&& ptr = {};",
Style);

diff  --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index df1b05226747..a2474d5c10f8 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -111,6 +111,9 @@ TEST_F(TokenAnnotatorTest, UnderstandsUsesOfStarAndAmp) {
 "} & = {};");
   EXPECT_EQ(Tokens.size(), 10u) << Tokens;
   EXPECT_TOKEN(Tokens[3], tok::ampamp, TT_PointerOrReference);
+  Tokens = annotate("int i = int{42} * 2;");
+  EXPECT_EQ(Tokens.size(), 11u) << Tokens;
+  EXPECT_TOKEN(Tokens[7], tok::star, TT_BinaryOperator);
 }
 
 TEST_F(TokenAnnotatorTest, UnderstandsUsesOfPlusAndMinus) {



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 8f2ba36 - Revert "[ARM][Thumb] Command-line option to ensure AAPCS compliant Frame Records AND [NFC][Thumb] Update frame-chain codegen test to use thumbv6m"

2022-06-15 Thread Krasimir Georgiev via cfe-commits

Author: Krasimir Georgiev
Date: 2022-06-15T16:10:02+02:00
New Revision: 8f2ba3633646d0c67a1442c6508d02d93571b344

URL: 
https://github.com/llvm/llvm-project/commit/8f2ba3633646d0c67a1442c6508d02d93571b344
DIFF: 
https://github.com/llvm/llvm-project/commit/8f2ba3633646d0c67a1442c6508d02d93571b344.diff

LOG: Revert "[ARM][Thumb] Command-line option to ensure AAPCS compliant Frame 
Records AND [NFC][Thumb] Update frame-chain codegen test to use thumbv6m"

This reverts commit 7625e01d661644a560884057755d48a0da8b77b4 and
dependent cbcce82ef6b512d97e92a319a75a03e997c844e1.

Commit 7625e01d661644a560884057755d48a0da8b77b4 causes some new codegen test
failures under asan, e.g., CodeGen/ARM/execute-only.ll:
https://lab.llvm.org/buildbot/#/builders/5/builds/24659/steps/15/logs/stdio.

Added: 


Modified: 
clang/include/clang/Driver/Options.td
clang/lib/Driver/ToolChains/Arch/ARM.cpp
llvm/lib/Target/ARM/ARM.td
llvm/lib/Target/ARM/ARMBaseRegisterInfo.cpp
llvm/lib/Target/ARM/ARMCallingConv.td
llvm/lib/Target/ARM/ARMFrameLowering.cpp
llvm/lib/Target/ARM/ARMFrameLowering.h
llvm/lib/Target/ARM/ARMMachineFunctionInfo.h
llvm/lib/Target/ARM/ARMSubtarget.h
llvm/lib/Target/ARM/Thumb1FrameLowering.cpp
llvm/lib/Target/ARM/ThumbRegisterInfo.cpp
llvm/test/CodeGen/Thumb/frame-access.ll

Removed: 
llvm/test/CodeGen/ARM/frame-chain-reserved-fp.ll
llvm/test/CodeGen/ARM/frame-chain.ll
llvm/test/CodeGen/Thumb/frame-chain-reserved-fp.ll
llvm/test/CodeGen/Thumb/frame-chain.ll



diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index b40cb1167388e..5fa681f538194 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -3478,9 +3478,7 @@ defm aapcs_bitfield_width : BoolOption<"f", 
"aapcs-bitfield-width",
   BothFlags<[NoXarchOption, CC1Option], " the AAPCS standard requirement 
stating that"
 " volatile bit-field width is dictated by the field container 
type. (ARM only).">>,
   Group;
-def mframe_chain : Joined<["-"], "mframe-chain=">,
-  Group, Values<"none,aapcs,aapcs+leaf">,
-  HelpText<"Select the frame chain model used to emit frame records (Arm 
only).">;
+
 def mgeneral_regs_only : Flag<["-"], "mgeneral-regs-only">, Group,
   HelpText<"Generate code which only uses the general purpose registers 
(AArch64/x86 only)">;
 def mfix_cmse_cve_2021_35465 : Flag<["-"], "mfix-cmse-cve-2021-35465">,

diff  --git a/clang/lib/Driver/ToolChains/Arch/ARM.cpp 
b/clang/lib/Driver/ToolChains/Arch/ARM.cpp
index b79d1f00ea48b..dc6b35e39cfdd 100644
--- a/clang/lib/Driver/ToolChains/Arch/ARM.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/ARM.cpp
@@ -718,15 +718,6 @@ void arm::getARMTargetFeatures(const Driver , const 
llvm::Triple ,
 }
   }
 
-  // Propagate frame-chain model selection
-  if (Arg *A = Args.getLastArg(options::OPT_mframe_chain)) {
-StringRef FrameChainOption = A->getValue();
-if (FrameChainOption.startswith("aapcs"))
-  Features.push_back("+aapcs-frame-chain");
-if (FrameChainOption == "aapcs+leaf")
-  Features.push_back("+aapcs-frame-chain-leaf");
-  }
-
   // CMSE: Check for target 8M (for -mcmse to be applicable) is performed 
later.
   if (Args.getLastArg(options::OPT_mcmse))
 Features.push_back("+8msecext");

diff  --git a/llvm/lib/Target/ARM/ARM.td b/llvm/lib/Target/ARM/ARM.td
index 48559a89a30a0..e8970b916a5f0 100644
--- a/llvm/lib/Target/ARM/ARM.td
+++ b/llvm/lib/Target/ARM/ARM.td
@@ -546,16 +546,6 @@ def FeatureFixCortexA57AES1742098 : 
SubtargetFeature<"fix-cortex-a57-aes-1742098
   "FixCortexA57AES1742098", "true",
   "Work around Cortex-A57 Erratum 1742098 / Cortex-A72 Erratum 1655431 (AES)">;
 
-def FeatureAAPCSFrameChain : SubtargetFeature<"aapcs-frame-chain",
-  "CreateAAPCSFrameChain", "true",
-  "Create an AAPCS compliant frame 
chain">;
-
-def FeatureAAPCSFrameChainLeaf : SubtargetFeature<"aapcs-frame-chain-leaf",
-  "CreateAAPCSFrameChainLeaf", 
"true",
-  "Create an AAPCS compliant 
frame chain "
-  "for leaf functions",
-  [FeatureAAPCSFrameChain]>;
-
 
//===--===//
 // ARM architecture class
 //

diff  --git a/llvm/lib/Target/ARM/ARMBaseRegisterInfo.cpp 
b/llvm/lib/Target/ARM/ARMBaseRegisterInfo.cpp
index 1d0e743b94dbf..cae72e465c7bf 100644
--- a/llvm/lib/Target/ARM/ARMBaseRegisterInfo.cpp
+++ b/llvm/lib/Target/ARM/ARMBaseRegisterInfo.cpp
@@ -63,8 +63,12 @@ const MCPhysReg*
 ARMBaseRegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const {
   const ARMSubtarget  = MF->getSubtarget();
   bool 

[clang] be656df - [clang-format] add a regression test for include sorting

2022-04-28 Thread Krasimir Georgiev via cfe-commits

Author: Krasimir Georgiev
Date: 2022-04-28T11:02:14+02:00
New Revision: be656df18721dc55a1de2eea64a3f73b6afa29a2

URL: 
https://github.com/llvm/llvm-project/commit/be656df18721dc55a1de2eea64a3f73b6afa29a2
DIFF: 
https://github.com/llvm/llvm-project/commit/be656df18721dc55a1de2eea64a3f73b6afa29a2.diff

LOG: [clang-format] add a regression test for include sorting

This adds a regression test from the comments
on https://reviews.llvm.org/D121370.

Reviewed By: MyDeveloperDay, curdeius

Differential Revision: https://reviews.llvm.org/D124513

Added: 


Modified: 
clang/unittests/Format/SortIncludesTest.cpp

Removed: 




diff  --git a/clang/unittests/Format/SortIncludesTest.cpp 
b/clang/unittests/Format/SortIncludesTest.cpp
index 7becb906d5d5..97a494a0a467 100644
--- a/clang/unittests/Format/SortIncludesTest.cpp
+++ b/clang/unittests/Format/SortIncludesTest.cpp
@@ -458,6 +458,20 @@ TEST_F(SortIncludesTest, HandlesMultilineIncludes) {
  "#include \"b.h\"\n"));
 }
 
+TEST_F(SortIncludesTest, HandlesTrailingCommentsWithAngleBrackets) {
+  // Regression test from the discussion at https://reviews.llvm.org/D121370.
+  EXPECT_EQ("#include \n"
+"\n"
+"#include \"util/bar.h\"\n"
+"#include \"util/foo/foo.h\" // foo\n",
+sort("#include \n"
+ "\n"
+ "#include \"util/bar.h\"\n"
+ "#include \"util/foo/foo.h\" // foo\n",
+ /*FileName=*/"input.cc",
+ /*ExpectedNumRanges=*/0));
+}
+
 TEST_F(SortIncludesTest, LeavesMainHeaderFirst) {
   Style.IncludeIsMainRegex = "([-_](test|unittest))?$";
   EXPECT_EQ("#include \"llvm/a.h\"\n"



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] e8cc749 - Revert "[clang-format] SortIncludes should support "@import" lines in Objective-C"

2022-04-28 Thread Krasimir Georgiev via cfe-commits

Author: Krasimir Georgiev
Date: 2022-04-28T11:00:32+02:00
New Revision: e8cc7490d23477233d21c72923a4f8ea43bfbbc0

URL: 
https://github.com/llvm/llvm-project/commit/e8cc7490d23477233d21c72923a4f8ea43bfbbc0
DIFF: 
https://github.com/llvm/llvm-project/commit/e8cc7490d23477233d21c72923a4f8ea43bfbbc0.diff

LOG: Revert "[clang-format] SortIncludes should support "@import" lines in 
Objective-C"

This reverts commit d46fa023caa2db5a9f1e21dd038bcb626261d958.
Regressed include order in some cases with trailing comments, see the
comments on https://reviews.llvm.org/D121370. Will add a regression test
in a follow-up commit.

Added: 


Modified: 
clang/include/clang/Tooling/Inclusions/HeaderIncludes.h
clang/lib/Format/Format.cpp
clang/lib/Tooling/Inclusions/HeaderIncludes.cpp
clang/unittests/Format/SortIncludesTest.cpp

Removed: 




diff  --git a/clang/include/clang/Tooling/Inclusions/HeaderIncludes.h 
b/clang/include/clang/Tooling/Inclusions/HeaderIncludes.h
index a5017bf84c24a..ea8ad896be89f 100644
--- a/clang/include/clang/Tooling/Inclusions/HeaderIncludes.h
+++ b/clang/include/clang/Tooling/Inclusions/HeaderIncludes.h
@@ -129,23 +129,6 @@ class HeaderIncludes {
   llvm::Regex IncludeRegex;
 };
 
-/// \returns a regex that can match various styles of C++ includes.
-/// For example:
-/// \code
-/// #include 
-/// @import bar;
-/// #include "bar.h"
-/// \endcode
-llvm::Regex getCppIncludeRegex();
-
-/// \returns the last match in the list of matches that is not empty.
-llvm::StringRef getIncludeNameFromMatches(
-const llvm::SmallVectorImpl );
-
-/// \returns the given include name and removes the following symbols from the
-/// beginning and ending of the include name: " > < ;
-llvm::StringRef trimInclude(llvm::StringRef IncludeName);
-
 } // namespace tooling
 } // namespace clang
 

diff  --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index b2c710174ecd9..afa87a8bafe31 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -44,7 +44,6 @@
 #include "llvm/Support/VirtualFileSystem.h"
 #include "llvm/Support/YAMLTraits.h"
 #include 
-#include 
 #include 
 #include 
 #include 
@@ -2725,6 +2724,13 @@ static void sortCppIncludes(const FormatStyle ,
   }
 }
 
+namespace {
+
+const char CppIncludeRegexPattern[] =
+R"(^[\t\ ]*#[\t\ ]*(import|include)[^"<]*(["<][^">]*[">]))";
+
+} // anonymous namespace
+
 tooling::Replacements sortCppIncludes(const FormatStyle , StringRef Code,
   ArrayRef Ranges,
   StringRef FileName,
@@ -2734,7 +2740,7 @@ tooling::Replacements sortCppIncludes(const FormatStyle 
, StringRef Code,
   .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
   .Default(0);
   unsigned SearchFrom = 0;
-  llvm::Regex IncludeRegex(tooling::getCppIncludeRegex());
+  llvm::Regex IncludeRegex(CppIncludeRegexPattern);
   SmallVector Matches;
   SmallVector IncludesInBlock;
 
@@ -2790,14 +2796,7 @@ tooling::Replacements sortCppIncludes(const FormatStyle 
, StringRef Code,
 bool MergeWithNextLine = Trimmed.endswith("\\");
 if (!FormattingOff && !MergeWithNextLine) {
   if (IncludeRegex.match(Line, )) {
-StringRef IncludeName = tooling::getIncludeNameFromMatches(Matches);
-// This addresses https://github.com/llvm/llvm-project/issues/38995
-bool WithSemicolon = false;
-if (!IncludeName.startswith("\"") && !IncludeName.startswith("<") &&
-IncludeName.endswith(";")) {
-  WithSemicolon = true;
-}
-
+StringRef IncludeName = Matches[2];
 if (Line.contains("/*") && !Line.contains("*/")) {
   // #include with a start of a block comment, but without the end.
   // Need to keep all the lines until the end of the comment together.
@@ -2810,10 +2809,8 @@ tooling::Replacements sortCppIncludes(const FormatStyle 
, StringRef Code,
 int Category = Categories.getIncludePriority(
 IncludeName,
 /*CheckMainHeader=*/!MainIncludeFound && FirstIncludeBlock);
-int Priority = WithSemicolon ? std::numeric_limits::max()
- : Categories.getSortIncludePriority(
-   IncludeName, !MainIncludeFound &&
-FirstIncludeBlock);
+int Priority = Categories.getSortIncludePriority(
+IncludeName, !MainIncludeFound && FirstIncludeBlock);
 if (Category == 0)
   MainIncludeFound = true;
 IncludesInBlock.push_back(
@@ -3073,7 +3070,8 @@ namespace {
 
 inline bool isHeaderInsertion(const tooling::Replacement ) {
   return Replace.getOffset() == UINT_MAX && Replace.getLength() == 0 &&
- tooling::getCppIncludeRegex().match(Replace.getReplacementText());
+ 

[clang] be5c3ca - Revert "[clang-format] Correctly recognize arrays in template parameter list."

2022-03-24 Thread Krasimir Georgiev via cfe-commits

Author: Krasimir Georgiev
Date: 2022-03-24T10:14:13+01:00
New Revision: be5c3ca7fbaec90fff004af54d3cd5f6c30a9664

URL: 
https://github.com/llvm/llvm-project/commit/be5c3ca7fbaec90fff004af54d3cd5f6c30a9664
DIFF: 
https://github.com/llvm/llvm-project/commit/be5c3ca7fbaec90fff004af54d3cd5f6c30a9664.diff

LOG: Revert "[clang-format] Correctly recognize arrays in template parameter 
list."

This reverts commit 126b37a713dc1c67cbc7dc8b5288b2f907c906a9.

Regressed some ObjC patterns, see comments on https://reviews.llvm.org/D121584.

Added: 


Modified: 
clang/lib/Format/UnwrappedLineParser.cpp
clang/unittests/Format/TokenAnnotatorTest.cpp

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index b8cffcd471e91..c5594a6d66484 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -1940,11 +1940,6 @@ bool UnwrappedLineParser::tryToParseLambda() {
   if (!tryToParseLambdaIntroducer())
 return false;
 
-  // `[something] >` is not a lambda, but an array type in a template parameter
-  // list.
-  if (FormatTok->is(tok::greater))
-return false;
-
   bool SeenArrow = false;
   bool InTemplateParameterList = false;
 
@@ -3534,7 +3529,7 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
   // Don't try parsing a lambda if we had a closing parenthesis before,
   // it was probably a pointer to an array: int (*)[].
   if (!tryToParseLambda())
-continue;
+break;
 } else {
   parseSquare();
   continue;

diff  --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index ac0802f837173..380ec90330f12 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -98,20 +98,6 @@ TEST_F(TokenAnnotatorTest, UnderstandsStructs) {
   auto Tokens = annotate("struct S {};");
   EXPECT_EQ(Tokens.size(), 6u) << Tokens;
   EXPECT_TOKEN(Tokens[2], tok::l_brace, TT_StructLBrace);
-
-  Tokens = annotate("template  struct S {};");
-  EXPECT_EQ(Tokens.size(), 18u) << Tokens;
-  EXPECT_TOKEN(Tokens[7], tok::less, TT_TemplateOpener);
-  EXPECT_TOKEN(Tokens[10], tok::l_square, TT_ArraySubscriptLSquare);
-  EXPECT_TOKEN(Tokens[13], tok::greater, TT_TemplateCloser);
-  EXPECT_TOKEN(Tokens[14], tok::l_brace, TT_StructLBrace);
-
-  Tokens = annotate("template  struct S {};");
-  EXPECT_EQ(Tokens.size(), 18u) << Tokens;
-  EXPECT_TOKEN(Tokens[7], tok::less, TT_TemplateOpener);
-  EXPECT_TOKEN(Tokens[10], tok::l_square, TT_ArraySubscriptLSquare);
-  EXPECT_TOKEN(Tokens[13], tok::greater, TT_TemplateCloser);
-  EXPECT_TOKEN(Tokens[14], tok::l_brace, TT_StructLBrace);
 }
 
 TEST_F(TokenAnnotatorTest, UnderstandsUnions) {



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] eb35e0e - [clang-format] don't break up #-style comment sections

2022-03-22 Thread Krasimir Georgiev via cfe-commits

Author: Krasimir Georgiev
Date: 2022-03-22T15:29:02+01:00
New Revision: eb35e0ecbe0ae153481f1df16d91cc6001477d21

URL: 
https://github.com/llvm/llvm-project/commit/eb35e0ecbe0ae153481f1df16d91cc6001477d21
DIFF: 
https://github.com/llvm/llvm-project/commit/eb35e0ecbe0ae153481f1df16d91cc6001477d21.diff

LOG: [clang-format] don't break up #-style comment sections

Follow-up from 
https://github.com/llvm/llvm-project/commit/36d13d3f8adb3d1a6bae71370afa23d11a94dc78;
 https://reviews.llvm.org/D121451.

Restore the old behavior in situations where we use # as comments and long 
strings of #'s for comment sections.

Reviewed By: MyDeveloperDay

Differential Revision: https://reviews.llvm.org/D122230

Added: 


Modified: 
clang/lib/Format/BreakableToken.cpp
clang/unittests/Format/FormatTestTextProto.cpp

Removed: 




diff  --git a/clang/lib/Format/BreakableToken.cpp 
b/clang/lib/Format/BreakableToken.cpp
index db7361bf5f2ff..94bd9823e1f5a 100644
--- a/clang/lib/Format/BreakableToken.cpp
+++ b/clang/lib/Format/BreakableToken.cpp
@@ -785,7 +785,16 @@ BreakableLineCommentSection::BreakableLineCommentSection(
 Lines[i].substr(IndentPrefix.size(), FirstCharByteSize),
 Encoding) != 1)
   return false;
-if (FirstCommentChar == '#')
+// In C-like comments, add a space before #. For example this is useful
+// to preserve the relative indentation when commenting out code with
+// #includes.
+//
+// In languages using # as the comment leader such as proto, don't
+// add a space to support patterns like:
+// #
+// # section
+// #
+if (FirstCommentChar == '#' && !TokenText.startswith("#"))
   return false;
 return FirstCommentChar == '\\' || isPunctuation(FirstCommentChar) ||
isHorizontalWhitespace(FirstCommentChar);

diff  --git a/clang/unittests/Format/FormatTestTextProto.cpp 
b/clang/unittests/Format/FormatTestTextProto.cpp
index 44b67d275bcc3..10a43c1519d6d 100644
--- a/clang/unittests/Format/FormatTestTextProto.cpp
+++ b/clang/unittests/Format/FormatTestTextProto.cpp
@@ -408,6 +408,23 @@ TEST_F(FormatTestTextProto, UnderstandsHashComments) {
"dd: 100\n"
" another quadriple-hash comment\n",
Style));
+
+  // Ensure we support a common pattern for naming sections.
+  EXPECT_EQ("##\n"
+"# section name\n"
+"##",
+format("##\n"
+   "# section name\n"
+   "##",
+   Style));
+
+  EXPECT_EQ("///\n"
+"// section name\n"
+"///",
+format("///\n"
+   "// section name\n"
+   "///",
+   Style));
 }
 
 TEST_F(FormatTestTextProto, FormatsExtensions) {



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] c9592ae - [clang-format] Fix preprocessor nesting after commit 529aa4b011c4ae808d658022ef643c44dd9b2c9c

2022-02-22 Thread Krasimir Georgiev via cfe-commits

Author: Krasimir Georgiev
Date: 2022-02-22T15:43:18+01:00
New Revision: c9592ae49b8c486754a745e0c7b1a30b92a12e8b

URL: 
https://github.com/llvm/llvm-project/commit/c9592ae49b8c486754a745e0c7b1a30b92a12e8b
DIFF: 
https://github.com/llvm/llvm-project/commit/c9592ae49b8c486754a745e0c7b1a30b92a12e8b.diff

LOG: [clang-format] Fix preprocessor nesting after commit 
529aa4b011c4ae808d658022ef643c44dd9b2c9c

In 
https://github.com/llvm/llvm-project/commit/529aa4b011c4ae808d658022ef643c44dd9b2c9c
by setting the identifier info to nullptr, we started to subtly
interfere with the parts in the beginning of the function,
https://github.com/llvm/llvm-project/blob/529aa4b011c4ae808d658022ef643c44dd9b2c9c/clang/lib/Format/UnwrappedLineParser.cpp#L991
causing the preprocessor nesting to change in some cases. E.g., for the
added regression test, clang-format started incorrectly guessing the
language as C++.

This tries to address this by introducing an internal identifier info
element to use instead.

Reviewed By: curdeius, MyDeveloperDay

Differential Revision: https://reviews.llvm.org/D120315

Added: 


Modified: 
clang/lib/Format/FormatToken.h
clang/lib/Format/UnwrappedLineParser.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index 5f05986addf6a..bd1d447328a0a 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -949,6 +949,10 @@ struct AdditionalKeywords {
 kw_slots = ("slots");
 kw_qslots = ("Q_SLOTS");
 
+// For internal clang-format use.
+kw_internal_ident_after_define =
+("__CLANG_FORMAT_INTERNAL_IDENT_AFTER_DEFINE__");
+
 // C# keywords
 kw_dollar = ("dollar");
 kw_base = ("base");
@@ -1069,6 +1073,9 @@ struct AdditionalKeywords {
   IdentifierInfo *kw_slots;
   IdentifierInfo *kw_qslots;
 
+  // For internal use by clang-format.
+  IdentifierInfo *kw_internal_ident_after_define;
+
   // C# keywords
   IdentifierInfo *kw_dollar;
   IdentifierInfo *kw_base;

diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 7d29afb0c042c..09e209e856541 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -1089,9 +1089,10 @@ void UnwrappedLineParser::parsePPDefine() {
   // In the context of a define, even keywords should be treated as normal
   // identifiers. Setting the kind to identifier is not enough, because we need
   // to treat additional keywords like __except as well, which are already
-  // identifiers.
+  // identifiers. Setting the identifier info to null interferes with include
+  // guard processing above, and changes preprocessing nesting.
   FormatTok->Tok.setKind(tok::identifier);
-  FormatTok->Tok.setIdentifierInfo(nullptr);
+  FormatTok->Tok.setIdentifierInfo(Keywords.kw_internal_ident_after_define);
   nextToken();
   if (FormatTok->Tok.getKind() == tok::l_paren &&
   !FormatTok->hasWhitespaceBefore())

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 51f6239bf2100..7d8b74c9c455f 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -22724,6 +22724,13 @@ TEST_F(FormatTest, FileAndCode) {
   EXPECT_EQ(
   FormatStyle::LK_Cpp,
   guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;"));
+  // Only one of the two preprocessor regions has ObjC-like code.
+  EXPECT_EQ(FormatStyle::LK_ObjC,
+guessLanguage("foo.h", "#if A\n"
+   "#define B() C\n"
+   "#else\n"
+   "#define B() [NSString a:@\"\"]\n"
+   "#endif\n"));
 }
 
 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) {



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 969a51f - Revert "[ASan] Moved optimized callbacks into a separate library."

2021-12-24 Thread Krasimir Georgiev via cfe-commits

Author: Krasimir Georgiev
Date: 2021-12-24T12:01:36+01:00
New Revision: 969a51ff363263a3b5f2df55eba6b4d392bf30c0

URL: 
https://github.com/llvm/llvm-project/commit/969a51ff363263a3b5f2df55eba6b4d392bf30c0
DIFF: 
https://github.com/llvm/llvm-project/commit/969a51ff363263a3b5f2df55eba6b4d392bf30c0.diff

LOG: Revert "[ASan] Moved optimized callbacks into a separate library."

We need some internal updates for this, shared directly with the author.

This reverts commit 71b3bfde9cd296525bbf5b1619e199074156d12b.

Added: 


Modified: 
clang/lib/Driver/ToolChains/CommonArgs.cpp
clang/test/Driver/sanitizer-ld.c
compiler-rt/lib/asan/CMakeLists.txt
compiler-rt/lib/asan/tests/CMakeLists.txt

Removed: 
compiler-rt/lib/asan/asan_rtl_static.cpp



diff  --git a/clang/lib/Driver/ToolChains/CommonArgs.cpp 
b/clang/lib/Driver/ToolChains/CommonArgs.cpp
index 267625c70b251..407f81a2ae09a 100644
--- a/clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ b/clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -826,11 +826,6 @@ collectSanitizerRuntimes(const ToolChain , const 
ArgList ,
   if (SanArgs.needsStatsRt() && SanArgs.linkRuntimes())
 StaticRuntimes.push_back("stats_client");
 
-  // Always link the static runtime regardless of DSO or executable.
-  if (SanArgs.needsAsanRt()) {
-HelperStaticRuntimes.push_back("asan_static");
-  }
-
   // Collect static runtimes.
   if (Args.hasArg(options::OPT_shared)) {
 // Don't link static runtimes into DSOs.

diff  --git a/clang/test/Driver/sanitizer-ld.c 
b/clang/test/Driver/sanitizer-ld.c
index ea8c49f2384ad..d62e19fd4021b 100644
--- a/clang/test/Driver/sanitizer-ld.c
+++ b/clang/test/Driver/sanitizer-ld.c
@@ -22,7 +22,7 @@
 // RUN: --sysroot=%S/Inputs/basic_linux_tree \
 // RUN:   | FileCheck --check-prefix=CHECK-ASAN-NO-LINK-RUNTIME-LINUX %s
 //
-// CHECK-ASAN-NO-LINK-RUNTIME-LINUX-NOT: libclang_rt.asan-x86_64
+// CHECK-ASAN-NO-LINK-RUNTIME-LINUX-NOT: libclang_rt.asan
 
 // RUN: %clang -no-canonical-prefixes %s -### -o %t.o 2>&1 \
 // RUN: -target i386-unknown-linux -fuse-ld=ld -fsanitize=address 
-shared-libsan \

diff  --git a/compiler-rt/lib/asan/CMakeLists.txt 
b/compiler-rt/lib/asan/CMakeLists.txt
index b79b7278f6dbb..2e63c8d051688 100644
--- a/compiler-rt/lib/asan/CMakeLists.txt
+++ b/compiler-rt/lib/asan/CMakeLists.txt
@@ -34,6 +34,7 @@ set(ASAN_SOURCES
 
 if (NOT WIN32 AND NOT APPLE)
   list(APPEND ASAN_SOURCES
+asan_rtl_x86_64.S
 asan_interceptors_vfork.S
 )
 endif()
@@ -42,16 +43,6 @@ set(ASAN_CXX_SOURCES
   asan_new_delete.cpp
   )
 
-set(ASAN_STATIC_SOURCES
-  asan_rtl_static.cpp
-  )
-
-if (NOT WIN32 AND NOT APPLE)
-  list(APPEND ASAN_STATIC_SOURCES
-asan_rtl_x86_64.S
-  )
-endif()
-
 set(ASAN_PREINIT_SOURCES
   asan_preinit.cpp
   )
@@ -144,12 +135,6 @@ if(NOT APPLE)
 ADDITIONAL_HEADERS ${ASAN_HEADERS}
 CFLAGS ${ASAN_CFLAGS}
 DEFS ${ASAN_COMMON_DEFINITIONS})
-  add_compiler_rt_object_libraries(RTAsan_static
-ARCHS ${ASAN_SUPPORTED_ARCH}
-SOURCES ${ASAN_STATIC_SOURCES}
-ADDITIONAL_HEADERS ${ASAN_HEADERS}
-CFLAGS ${ASAN_CFLAGS}
-DEFS ${ASAN_COMMON_DEFINITIONS})
   add_compiler_rt_object_libraries(RTAsan_preinit
 ARCHS ${ASAN_SUPPORTED_ARCH}
 SOURCES ${ASAN_PREINIT_SOURCES}
@@ -191,14 +176,6 @@ if(APPLE)
 LINK_FLAGS ${WEAK_SYMBOL_LINK_FLAGS}
 DEFS ${ASAN_DYNAMIC_DEFINITIONS}
 PARENT_TARGET asan)
-
-  add_compiler_rt_runtime(clang_rt.asan_static
-STATIC
-ARCHS ${ASAN_SUPPORTED_ARCH}
-OBJECT_LIBS RTAsan_static
-CFLAGS ${ASAN_CFLAGS}
-DEFS ${ASAN_COMMON_DEFINITIONS}
-PARENT_TARGET asan)
 else()
   # Build separate libraries for each target.
 
@@ -230,14 +207,6 @@ else()
 DEFS ${ASAN_COMMON_DEFINITIONS}
 PARENT_TARGET asan)
 
-  add_compiler_rt_runtime(clang_rt.asan_static
-STATIC
-ARCHS ${ASAN_SUPPORTED_ARCH}
-OBJECT_LIBS RTAsan_static
-CFLAGS ${ASAN_CFLAGS}
-DEFS ${ASAN_COMMON_DEFINITIONS}
-PARENT_TARGET asan)
-
   add_compiler_rt_runtime(clang_rt.asan-preinit
 STATIC
 ARCHS ${ASAN_SUPPORTED_ARCH}

diff  --git a/compiler-rt/lib/asan/asan_rtl_static.cpp 
b/compiler-rt/lib/asan/asan_rtl_static.cpp
deleted file mode 100644
index 74e6eb0ddf1cf..0
--- a/compiler-rt/lib/asan/asan_rtl_static.cpp
+++ /dev/null
@@ -1,15 +0,0 @@
-//===-- asan_static_rtl.cpp 
---===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===--===//
-//
-// This file is a part of AddressSanitizer, an address sanity checker.
-//
-// Main file of the ASan run-time library.
-//===--===//
-
-// This file is empty 

[clang] 3a3fcd6 - [clang-format] add regression tests for braced lists

2021-12-19 Thread Krasimir Georgiev via cfe-commits

Author: Krasimir Georgiev
Date: 2021-12-19T16:07:07+01:00
New Revision: 3a3fcd6a23ad2c0f420a2f6bfde7541233790a30

URL: 
https://github.com/llvm/llvm-project/commit/3a3fcd6a23ad2c0f420a2f6bfde7541233790a30
DIFF: 
https://github.com/llvm/llvm-project/commit/3a3fcd6a23ad2c0f420a2f6bfde7541233790a30.diff

LOG: [clang-format] add regression tests for braced lists

Depends on https://reviews.llvm.org/D116000.

Added test cases from the comments on https://reviews.llvm.org/D114583.

Reviewed By: MyDeveloperDay

Differential Revision: https://reviews.llvm.org/D116001

Added: 


Modified: 
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index d12796e32e577..9325f622d228e 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -11515,6 +11515,17 @@ TEST_F(FormatTest, LayoutCxx11BraceInitializers) {
"  };\n"
"};");
   verifyFormat("#define A {a, a},");
+  // Don't confuse braced list initializers with compound statements.
+  verifyFormat(
+  "class A {\n"
+  "  A() : a{} {}\n"
+  "  A(int b) : b(b) {}\n"
+  "  A(int a, int b) : a(a), bs{{bs...}} { f(); }\n"
+  "  int a, b;\n"
+  "  explicit Expr(const Scalar ) : u{Constant{x}} {}\n"
+  "  explicit Expr(Scalar &) : u{Constant{std::move(x)}} 
"
+  "{}\n"
+  "};");
 
   // Avoid breaking between equal sign and opening brace
   FormatStyle AvoidBreakingFirstArgument = getLLVMStyle();



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] d96bf6e - Revert "[clang-format] Adjust braced list detection"

2021-12-19 Thread Krasimir Georgiev via cfe-commits

Author: Krasimir Georgiev
Date: 2021-12-19T16:04:42+01:00
New Revision: d96bf6ea461810f7def54541dbcb7ceaecd2d065

URL: 
https://github.com/llvm/llvm-project/commit/d96bf6ea461810f7def54541dbcb7ceaecd2d065
DIFF: 
https://github.com/llvm/llvm-project/commit/d96bf6ea461810f7def54541dbcb7ceaecd2d065.diff

LOG: Revert "[clang-format] Adjust braced list detection"

It appears that this regressed the formatting of initializer lists in some
cases, see comments on https://reviews.llvm.org/D114583. I'll follow-up
by adding regression tests for these.

This reverts commit c41b3b0fa0f4f70aad8deaf48bcd42a04385066c.

Reviewed By: MyDeveloperDay

Differential Revision: https://reviews.llvm.org/D116000

Added: 


Modified: 
clang/lib/Format/UnwrappedLineParser.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 856efbd91cb01..c34d515a32d65 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -578,14 +578,17 @@ void UnwrappedLineParser::calculateBraceTypes(bool 
ExpectClassBody) {
   // BlockKind later if we parse a braced list (where all blocks
   // inside are by default braced lists), or when we explicitly detect
   // blocks (for example while parsing lambdas).
+  // FIXME: Some of these do not apply to JS, e.g. "} {" can never be a
+  // braced list in JS.
   ProbablyBracedList =
   (Style.Language == FormatStyle::LK_JavaScript &&
NextTok->isOneOf(Keywords.kw_of, Keywords.kw_in,
 Keywords.kw_as)) ||
   (Style.isCpp() && NextTok->is(tok::l_paren)) ||
   NextTok->isOneOf(tok::comma, tok::period, tok::colon,
-   tok::r_paren, tok::r_square, tok::ellipsis) ||
-  (NextTok->isOneOf(tok::l_brace, tok::identifier) &&
+   tok::r_paren, tok::r_square, tok::l_brace,
+   tok::ellipsis) ||
+  (NextTok->is(tok::identifier) &&
!PrevTok->isOneOf(tok::semi, tok::r_brace, tok::l_brace)) ||
   (NextTok->is(tok::semi) &&
(!ExpectClassBody || LBraceStack.size() != 1)) ||
@@ -2861,7 +2864,7 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
   // class Foo implements {bar: number} { }
   nextToken();
   if (FormatTok->is(tok::l_brace)) {
-parseBracedList();
+tryToParseBracedList();
 continue;
   }
 }

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 2a9de85bf453b..d12796e32e577 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -11867,27 +11867,6 @@ TEST_F(FormatTest, FormatsBracedListsInColumnLayout) {
"  f(v);\n"
"}");
 
-  verifyFormat("void foo() {\n"
-   "  { // asdf\n"
-   "{ int a; }\n"
-   "  }\n"
-   "  {\n"
-   "{ int b; }\n"
-   "  }\n"
-   "}");
-  verifyFormat("namespace n {\n"
-   "void foo() {\n"
-   "  {\n"
-   "{\n"
-   "  statement();\n"
-   "  if (false) {\n"
-   "  }\n"
-   "}\n"
-   "  }\n"
-   "  {}\n"
-   "}\n"
-   "} // namespace n");
-
   // Long lists should be formatted in columns even if they are nested.
   verifyFormat(
   "vector x = function({1, 22, 333, , 5, 66, 777,\n"



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] e708808 - [clang-format] Support TypeScript override keyword

2021-08-25 Thread Krasimir Georgiev via cfe-commits

Author: Jan Kuehle
Date: 2021-08-25T14:11:50+02:00
New Revision: e708808f875f58344ecaad66d9e6e167ca7ac90a

URL: 
https://github.com/llvm/llvm-project/commit/e708808f875f58344ecaad66d9e6e167ca7ac90a
DIFF: 
https://github.com/llvm/llvm-project/commit/e708808f875f58344ecaad66d9e6e167ca7ac90a.diff

LOG: [clang-format] Support TypeScript override keyword

TypeScript 4.3 added a new "override" keyword for class members. This
lets clang-format know about it, so it can format code using it
properly.

Reviewed By: krasimir

Differential Revision: https://reviews.llvm.org/D108692

Added: 


Modified: 
clang/lib/Format/FormatToken.h
clang/lib/Format/TokenAnnotator.cpp
clang/lib/Format/UnwrappedLineFormatter.cpp
clang/lib/Format/UnwrappedLineParser.cpp
clang/unittests/Format/FormatTestJS.cpp

Removed: 




diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index 0506cd554bcba..bbce27f799bc7 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -934,8 +934,8 @@ struct AdditionalKeywords {
 // already initialized.
 JsExtraKeywords = std::unordered_set(
 {kw_as, kw_async, kw_await, kw_declare, kw_finally, kw_from,
- kw_function, kw_get, kw_import, kw_is, kw_let, kw_module, kw_readonly,
- kw_set, kw_type, kw_typeof, kw_var, kw_yield,
+ kw_function, kw_get, kw_import, kw_is, kw_let, kw_module, kw_override,
+ kw_readonly, kw_set, kw_type, kw_typeof, kw_var, kw_yield,
  // Keywords from the Java section.
  kw_abstract, kw_extends, kw_implements, kw_instanceof, kw_interface});
 

diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 703eced09d446..887f6e363db82 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3957,8 +3957,9 @@ bool TokenAnnotator::canBreakBefore(const AnnotatedLine 
,
 tok::kw_return, Keywords.kw_yield, tok::kw_continue, tok::kw_break,
 tok::kw_throw, Keywords.kw_interface, Keywords.kw_type,
 tok::kw_static, tok::kw_public, tok::kw_private, tok::kw_protected,
-Keywords.kw_readonly, Keywords.kw_abstract, Keywords.kw_get,
-Keywords.kw_set, Keywords.kw_async, Keywords.kw_await))
+Keywords.kw_readonly, Keywords.kw_override, Keywords.kw_abstract,
+Keywords.kw_get, Keywords.kw_set, Keywords.kw_async,
+Keywords.kw_await))
   return false; // Otherwise automatic semicolon insertion would trigger.
 if (Right.NestingLevel == 0 &&
 (Left.Tok.getIdentifierInfo() ||

diff  --git a/clang/lib/Format/UnwrappedLineFormatter.cpp 
b/clang/lib/Format/UnwrappedLineFormatter.cpp
index cca85c1074de5..2577aea3a480d 100644
--- a/clang/lib/Format/UnwrappedLineFormatter.cpp
+++ b/clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -632,10 +632,11 @@ class LineJoiner {
 FormatToken *RecordTok = Line.First;
 // Skip record modifiers.
 while (RecordTok->Next &&
-   RecordTok->isOneOf(
-   tok::kw_typedef, tok::kw_export, Keywords.kw_declare,
-   Keywords.kw_abstract, tok::kw_default, tok::kw_public,
-   tok::kw_private, tok::kw_protected, Keywords.kw_internal))
+   RecordTok->isOneOf(tok::kw_typedef, tok::kw_export,
+  Keywords.kw_declare, Keywords.kw_abstract,
+  tok::kw_default, Keywords.kw_override,
+  tok::kw_public, tok::kw_private,
+  tok::kw_protected, Keywords.kw_internal))
   RecordTok = RecordTok->Next;
 if (RecordTok &&
 RecordTok->isOneOf(tok::kw_class, tok::kw_union, tok::kw_struct,

diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 8487875064aa8..18dc5c4244706 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -962,8 +962,8 @@ static bool mustBeJSIdent(const AdditionalKeywords 
,
   Keywords.kw_function, Keywords.kw_import, Keywords.kw_is,
   Keywords.kw_let, Keywords.kw_var, tok::kw_const,
   Keywords.kw_abstract, Keywords.kw_extends, 
Keywords.kw_implements,
-  Keywords.kw_instanceof, Keywords.kw_interface, 
Keywords.kw_throws,
-  Keywords.kw_from));
+  Keywords.kw_instanceof, Keywords.kw_interface,
+  Keywords.kw_override, Keywords.kw_throws, Keywords.kw_from));
 }
 
 static bool mustBeJSIdentOrValue(const AdditionalKeywords ,

diff  --git a/clang/unittests/Format/FormatTestJS.cpp 
b/clang/unittests/Format/FormatTestJS.cpp
index 311881dde273c..0c8329536 100644
--- a/clang/unittests/Format/FormatTestJS.cpp
+++ b/clang/unittests/Format/FormatTestJS.cpp
@@ -854,6 

[clang] befb9dc - [clang-format] keep TypeScript argument decorators in line

2021-08-24 Thread Krasimir Georgiev via cfe-commits

Author: Krasimir Georgiev
Date: 2021-08-24T12:37:08+02:00
New Revision: befb9dc3694e95355f21650de7acb058ac89f993

URL: 
https://github.com/llvm/llvm-project/commit/befb9dc3694e95355f21650de7acb058ac89f993
DIFF: 
https://github.com/llvm/llvm-project/commit/befb9dc3694e95355f21650de7acb058ac89f993.diff

LOG: [clang-format] keep TypeScript argument decorators in line

As a follow-up from https://reviews.llvm.org/D108538, ensure TypeScript
argument decorators are kept in line with the argument.

Reviewed By: MyDeveloperDay

Differential Revision: https://reviews.llvm.org/D108620

Added: 


Modified: 
clang/lib/Format/ContinuationIndenter.cpp
clang/unittests/Format/FormatTestJS.cpp

Removed: 




diff  --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index 9561e3489c40e..1bf63cb909e06 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -19,6 +19,7 @@
 #include "clang/Basic/OperatorPrecedence.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Format/Format.h"
+#include "llvm/ADT/StringSet.h"
 #include "llvm/Support/Debug.h"
 
 #define DEBUG_TYPE "format-indenter"
@@ -492,8 +493,12 @@ bool ContinuationIndenter::mustBreak(const LineState 
) {
   return true;
   }
 
-  // Break after the closing parenthesis of TypeScript decorators.
+  // Break after the closing parenthesis of TypeScript decorators before
+  // functions, getters and setters.
+  static const llvm::StringSet<> BreakBeforeDecoratedTokens = {"get", "set",
+   "function"};
   if (Style.Language == FormatStyle::LK_JavaScript &&
+  BreakBeforeDecoratedTokens.contains(Current.TokenText) &&
   Previous.is(tok::r_paren) && Previous.is(TT_JavaAnnotation)) {
 return true;
   }

diff  --git a/clang/unittests/Format/FormatTestJS.cpp 
b/clang/unittests/Format/FormatTestJS.cpp
index 8da822d0ccfc0..311881dde273c 100644
--- a/clang/unittests/Format/FormatTestJS.cpp
+++ b/clang/unittests/Format/FormatTestJS.cpp
@@ -701,8 +701,12 @@ TEST_F(FormatTestJS, FormatsFreestandingFunctions) {
getGoogleJSStyleWithColumns(20)));
 }
 
-TEST_F(FormatTestJS, FormatsDecoratedFunctions) {
-  // Regression test: ensure that there is a break before `get`.
+TEST_F(FormatTestJS, FormatsDecorators) {
+  // No line break after argument decorators.
+  verifyFormat("class A {\n"
+   "  constructor(@arg(DECOR) private arg: Type) {}\n"
+   "}");
+  // Ensure that there is a break before functions, getters and setters.
   EXPECT_EQ("class A {\n"
 "  private p = () => {}\n"
 "\n"
@@ -710,6 +714,24 @@ TEST_F(FormatTestJS, FormatsDecoratedFunctions) {
 "  get f() {\n"
 "return result;\n"
 "  }\n"
+"}\n"
+"\n"
+"class B {\n"
+"  private p = () => {}\n"
+"\n"
+"  @decorated('a')\n"
+"  set f() {\n"
+"return result;\n"
+"  }\n"
+"}\n"
+"\n"
+"class C {\n"
+"  private p = () => {}\n"
+"\n"
+"  @decorated('a')\n"
+"  function f() {\n"
+"return result;\n"
+"  }\n"
 "}",
 format("class A {\n"
"  private p = () => {}\n"
@@ -718,6 +740,24 @@ TEST_F(FormatTestJS, FormatsDecoratedFunctions) {
"  get f() {\n"
"return result;\n"
"  }\n"
+   "}\n"
+   "\n"
+   "class B {\n"
+   "  private p = () => {}\n"
+   "\n"
+   "  @decorated('a')\n"
+   "  set f() {\n"
+   "return result;\n"
+   "  }\n"
+   "}\n"
+   "\n"
+   "class C {\n"
+   "  private p = () => {}\n"
+   "\n"
+   "  @decorated('a')\n"
+   "  function f() {\n"
+   "return result;\n"
+   "  }\n"
"}",
getGoogleJSStyleWithColumns(50)));
 }



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] f3671a6 - [clang-format] break after the closing paren of a TypeScript decoration

2021-08-23 Thread Krasimir Georgiev via cfe-commits

Author: Krasimir Georgiev
Date: 2021-08-23T15:52:14+02:00
New Revision: f3671a688db2625ef3736ff3603ef7a9fb78610f

URL: 
https://github.com/llvm/llvm-project/commit/f3671a688db2625ef3736ff3603ef7a9fb78610f
DIFF: 
https://github.com/llvm/llvm-project/commit/f3671a688db2625ef3736ff3603ef7a9fb78610f.diff

LOG: [clang-format] break after the closing paren of a TypeScript decoration

This fixes up a regression we found from
https://reviews.llvm.org/D107267: in specific contexts, clang-format
stopped breaking after the `)` in TypeScript decorations. There were no test 
cases covering this, so I added one.

Reviewed By: MyDeveloperDay

Differential Revision: https://reviews.llvm.org/D108538

Added: 


Modified: 
clang/lib/Format/ContinuationIndenter.cpp
clang/unittests/Format/FormatTestJS.cpp

Removed: 




diff  --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index cdb112726b80d..9561e3489c40e 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -14,6 +14,7 @@
 #include "ContinuationIndenter.h"
 #include "BreakableToken.h"
 #include "FormatInternal.h"
+#include "FormatToken.h"
 #include "WhitespaceManager.h"
 #include "clang/Basic/OperatorPrecedence.h"
 #include "clang/Basic/SourceManager.h"
@@ -491,6 +492,12 @@ bool ContinuationIndenter::mustBreak(const LineState 
) {
   return true;
   }
 
+  // Break after the closing parenthesis of TypeScript decorators.
+  if (Style.Language == FormatStyle::LK_JavaScript &&
+  Previous.is(tok::r_paren) && Previous.is(TT_JavaAnnotation)) {
+return true;
+  }
+
   // If the return type spans multiple lines, wrap before the function name.
   if (((Current.is(TT_FunctionDeclarationName) &&
 // Don't break before a C# function when no break after return type

diff  --git a/clang/unittests/Format/FormatTestJS.cpp 
b/clang/unittests/Format/FormatTestJS.cpp
index 1c174e9e5b170..8da822d0ccfc0 100644
--- a/clang/unittests/Format/FormatTestJS.cpp
+++ b/clang/unittests/Format/FormatTestJS.cpp
@@ -701,6 +701,27 @@ TEST_F(FormatTestJS, FormatsFreestandingFunctions) {
getGoogleJSStyleWithColumns(20)));
 }
 
+TEST_F(FormatTestJS, FormatsDecoratedFunctions) {
+  // Regression test: ensure that there is a break before `get`.
+  EXPECT_EQ("class A {\n"
+"  private p = () => {}\n"
+"\n"
+"  @decorated('a')\n"
+"  get f() {\n"
+"return result;\n"
+"  }\n"
+"}",
+format("class A {\n"
+   "  private p = () => {}\n"
+   "\n"
+   "  @decorated('a')\n"
+   "  get f() {\n"
+   "return result;\n"
+   "  }\n"
+   "}",
+   getGoogleJSStyleWithColumns(50)));
+}
+
 TEST_F(FormatTestJS, GeneratorFunctions) {
   verifyFormat("function* f() {\n"
"  let x = 1;\n"



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 4593492 - [clang-format] improve distinction of K function definitions vs attributes

2021-08-12 Thread Krasimir Georgiev via cfe-commits

Author: Krasimir Georgiev
Date: 2021-08-12T10:29:06+02:00
New Revision: 45934922fa88b7542c8bcd86889d062fb78efdda

URL: 
https://github.com/llvm/llvm-project/commit/45934922fa88b7542c8bcd86889d062fb78efdda
DIFF: 
https://github.com/llvm/llvm-project/commit/45934922fa88b7542c8bcd86889d062fb78efdda.diff

LOG: [clang-format] improve distinction of K function definitions vs 
attributes

After
https://github.com/llvm/llvm-project/commit/9da70ab3d43c79116f80fc06aa7cf517374ce42c
we saw a few regressions around trailing attribute definitions and in
typedefs (examples in the added test cases). There's some tension
distinguishing K definitions from attributes at the parser level,
where we have to decide if we need to put the type of the K definition
on a new unwrapped line before we have access to the rest of the line,
so we're scanning backwards and looking for a pattern like f(a, b). But
this type of pattern could also be an attribute macro, or the whole
declaration could be a typedef itself. I updated the code to check for a
typedef at the beginning of the line and to not consider raw identifiers
as possible first K declaration (but treated as an attribute macro
instead). This is not 100% correct heuristic, but I think it should be
reasonably good in practice, where we'll:
  * likely be in some very C-ish code when using K style (e.g., stuff
that uses `struct name a;` instead of `name a;`
  * likely be in some very C++-ish code when using attributes
  * unlikely mix up the two in the same declaration.

Ideally, we should only decide to add the unwrapped line before the K
declaration after we've scanned the rest of the line an noticed the
variable declarations and the semicolon, but the way the parser is
organized I don't see a good way to do this in the current parser, which
only has good context for the previously visited tokens. I also tried
not emitting an unwrapped line there and trying to resolve the situation
later in the token annotator and the continuation indenter, and that
approach seems promising, but I couldn't make it to work without
messing up a bunch of other cases in unit tests.

Reviewed By: MyDeveloperDay

Differential Revision: https://reviews.llvm.org/D107950

Added: 


Modified: 
clang/lib/Format/UnwrappedLineParser.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index d6b1ebb1239d..0c4cacab5050 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -14,6 +14,7 @@
 
 #include "UnwrappedLineParser.h"
 #include "FormatToken.h"
+#include "clang/Basic/TokenKinds.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/raw_ostream.h"
@@ -1007,7 +1008,7 @@ static bool isC78ParameterDecl(const FormatToken *Tok) {
 
   if (!Tok->isOneOf(tok::kw_int, tok::kw_char, tok::kw_float, tok::kw_double,
 tok::kw_struct, tok::kw_union, tok::kw_long, tok::kw_short,
-tok::kw_unsigned, tok::kw_register, tok::identifier))
+tok::kw_unsigned, tok::kw_register))
 return false;
 
   Tok = Tok->Previous;
@@ -1378,7 +1379,8 @@ void UnwrappedLineParser::parseStructuralElement(bool 
IsTopLevel) {
 break;
   if (Previous->Previous && Previous->Previous->is(tok::at))
 break;
-  if (isC78ParameterDecl(FormatTok)) {
+  if (!Line->Tokens.begin()->Tok->is(tok::kw_typedef) &&
+  isC78ParameterDecl(FormatTok)) {
 addUnwrappedLine();
 return;
   }

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 670788caac00..1283aa67b337 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -8247,14 +8247,25 @@ TEST_F(FormatTest, ReturnTypeBreakingStyle) {
"  return a + b < c;\n"
"};",
Style);
-  // The return breaking style doesn't affect object definitions with
-  // attribute-like macros.
+
+  // The return breaking style doesn't affect:
+  // * function and object definitions with attribute-like macros
   verifyFormat("Tttt ppp\n"
"ABSL_GUARDED_BY(mutex) = {};",
getGoogleStyleWithColumns(40));
   verifyFormat("Tttt ppp\n"
"ABSL_GUARDED_BY(mutex);  // comment",
getGoogleStyleWithColumns(40));
+  verifyFormat("Tttt ppp\n"
+   "ABSL_GUARDED_BY(mutex1)\n"
+   "ABSL_GUARDED_BY(mutex2);",
+   getGoogleStyleWithColumns(40));
+  verifyFormat("Tt f(int a, int b)\n"
+   "ABSL_GUARDED_BY(mutex1)\n"
+   "ABSL_GUARDED_BY(mutex2);",
+   

[clang] 0fc27ef - [clang-format] handle trailing comments in function definition detection

2021-08-12 Thread Krasimir Georgiev via cfe-commits

Author: Krasimir Georgiev
Date: 2021-08-12T08:55:54+02:00
New Revision: 0fc27ef19670676689d3317948c81eb171bb25f8

URL: 
https://github.com/llvm/llvm-project/commit/0fc27ef19670676689d3317948c81eb171bb25f8
DIFF: 
https://github.com/llvm/llvm-project/commit/0fc27ef19670676689d3317948c81eb171bb25f8.diff

LOG: [clang-format] handle trailing comments in function definition detection

A follow-up to
https://github.com/llvm/llvm-project/commit/f6bc614546e169bb1b17a29c422ebace038e6c62
where we handle the case where the semicolon is followed by a trailing
comment.

Reviewed By: MyDeveloperDay

Differential Revision: https://reviews.llvm.org/D107907

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index de3dabcfc639..703eced09d44 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2482,7 +2482,7 @@ static bool isFunctionDeclarationName(const FormatToken 
,
   // return i + 1;
   //   }
   if (Next->Next && Next->Next->is(tok::identifier) &&
-  Line.Last->isNot(tok::semi))
+  !Line.endsWith(tok::semi))
 return true;
   for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen;
Tok = Tok->Next) {

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index de6f1b784394..670788caac00 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -8252,6 +8252,9 @@ TEST_F(FormatTest, ReturnTypeBreakingStyle) {
   verifyFormat("Tttt ppp\n"
"ABSL_GUARDED_BY(mutex) = {};",
getGoogleStyleWithColumns(40));
+  verifyFormat("Tttt ppp\n"
+   "ABSL_GUARDED_BY(mutex);  // comment",
+   getGoogleStyleWithColumns(40));
 
   Style = getGNUStyle();
 



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] f6bc614 - [clan-format] detect function definitions more conservatively

2021-08-03 Thread Krasimir Georgiev via cfe-commits

Author: Krasimir Georgiev
Date: 2021-08-03T16:19:35+02:00
New Revision: f6bc614546e169bb1b17a29c422ebace038e6c62

URL: 
https://github.com/llvm/llvm-project/commit/f6bc614546e169bb1b17a29c422ebace038e6c62
DIFF: 
https://github.com/llvm/llvm-project/commit/f6bc614546e169bb1b17a29c422ebace038e6c62.diff

LOG: [clan-format] detect function definitions more conservatively

https://reviews.llvm.org/D105964 updated the detection of function
definitions. It had the unfortunate effect to start marking object
definitions with attribute-like macros as function definitions.

This addresses this issue.

Reviewed By: owenpan

Differential Revision: https://reviews.llvm.org/D107269

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 54e6c7d38e7d..de3dabcfc639 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2482,7 +2482,7 @@ static bool isFunctionDeclarationName(const FormatToken 
,
   // return i + 1;
   //   }
   if (Next->Next && Next->Next->is(tok::identifier) &&
-  !(Next->MatchingParen->Next && Next->MatchingParen->Next->is(tok::semi)))
+  Line.Last->isNot(tok::semi))
 return true;
   for (const FormatToken *Tok = Next->Next; Tok && Tok != Next->MatchingParen;
Tok = Tok->Next) {

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index c328bd44744a..de6f1b784394 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -8224,7 +8224,12 @@ TEST_F(FormatTest, ReturnTypeBreakingStyle) {
"f(i)\n"
"{\n"
"  return i + 1;\n"
-   "}",
+   "}\n"
+   "int\n" // Break here.
+   "f(i)\n"
+   "{\n"
+   "  return i + 1;\n"
+   "};",
Style);
   verifyFormat("int f(a, b, c);\n" // No break here.
"int\n" // Break here.
@@ -8233,8 +8238,20 @@ TEST_F(FormatTest, ReturnTypeBreakingStyle) {
"float c;\n"
"{\n"
"  return a + b < c;\n"
-   "}",
+   "}\n"
+   "int\n"// Break here.
+   "f(a, b, c)\n" // Break here.
+   "short a, b;\n"
+   "float c;\n"
+   "{\n"
+   "  return a + b < c;\n"
+   "};",
Style);
+  // The return breaking style doesn't affect object definitions with
+  // attribute-like macros.
+  verifyFormat("Tttt ppp\n"
+   "ABSL_GUARDED_BY(mutex) = {};",
+   getGoogleStyleWithColumns(40));
 
   Style = getGNUStyle();
 



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 4f4f278 - [clang-format] don't break between function and function name in JS

2021-08-03 Thread Krasimir Georgiev via cfe-commits

Author: Krasimir Georgiev
Date: 2021-08-03T11:18:21+02:00
New Revision: 4f4f2783056fd01182740251b2ce8a77b12684b3

URL: 
https://github.com/llvm/llvm-project/commit/4f4f2783056fd01182740251b2ce8a77b12684b3
DIFF: 
https://github.com/llvm/llvm-project/commit/4f4f2783056fd01182740251b2ce8a77b12684b3.diff

LOG: [clang-format] don't break between function and function name in JS

The patch https://reviews.llvm.org/D105964 
(https://github.com/llvm/llvm-project/commit/58494c856a15f5b0e886c7baf5d505ac6c05dfe5)
updated detection of function declaration names. It had the unfortunate
consequence that it started breaking between `function` and the function
name in some cases in JavaScript code.

This patch addresses this.

Reviewed By: MyDeveloperDay, owenpan

Differential Revision: https://reviews.llvm.org/D107267

Added: 


Modified: 
clang/lib/Format/ContinuationIndenter.cpp
clang/unittests/Format/FormatTestJS.cpp

Removed: 




diff  --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index 8fbc15f27922a..cdb112726b80d 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -495,7 +495,10 @@ bool ContinuationIndenter::mustBreak(const LineState 
) {
   if (((Current.is(TT_FunctionDeclarationName) &&
 // Don't break before a C# function when no break after return type
 (!Style.isCSharp() ||
- Style.AlwaysBreakAfterReturnType != FormatStyle::RTBS_None)) ||
+ Style.AlwaysBreakAfterReturnType != FormatStyle::RTBS_None) &&
+// Don't always break between a JavaScript `function` and the function
+// name.
+Style.Language != FormatStyle::LK_JavaScript) ||
(Current.is(tok::kw_operator) && !Previous.is(tok::coloncolon))) &&
   !Previous.is(tok::kw_template) && 
State.Stack.back().BreakBeforeParameter)
 return true;

diff  --git a/clang/unittests/Format/FormatTestJS.cpp 
b/clang/unittests/Format/FormatTestJS.cpp
index c92c81f66a870..1c174e9e5b170 100644
--- a/clang/unittests/Format/FormatTestJS.cpp
+++ b/clang/unittests/Format/FormatTestJS.cpp
@@ -692,6 +692,13 @@ TEST_F(FormatTestJS, FormatsFreestandingFunctions) {
"  let x = 1;\n"
"  console.log(x);\n"
"}\n");
+  EXPECT_EQ("a = function(x) {}\n"
+"\n"
+"function f(x) {}",
+format("a = function(x) {}\n"
+   "\n"
+   "function f(x) {}",
+   getGoogleJSStyleWithColumns(20)));
 }
 
 TEST_F(FormatTestJS, GeneratorFunctions) {



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 54bd95c - [clang-format] distinguish function type casts after 21c18d5a04316891110cecc2bf37ce51533decba

2021-06-15 Thread Krasimir Georgiev via cfe-commits

Author: Krasimir Georgiev
Date: 2021-06-15T10:28:36+02:00
New Revision: 54bd95cd96bc7305219b594f95d7d1f447ee4c94

URL: 
https://github.com/llvm/llvm-project/commit/54bd95cd96bc7305219b594f95d7d1f447ee4c94
DIFF: 
https://github.com/llvm/llvm-project/commit/54bd95cd96bc7305219b594f95d7d1f447ee4c94.diff

LOG: [clang-format] distinguish function type casts after 
21c18d5a04316891110cecc2bf37ce51533decba

https://github.com/llvm/llvm-project/commit/21c18d5a04316891110cecc2bf37ce51533decba
improved the detection of multiplication in function call argument lists,
but unintentionally regressed the handling of function type casts (there
were no tests covering those).
This patch improves the detection of function type casts and adds a few tests.

Reviewed By: HazardyKnusperkeks

Differential Revision: https://reviews.llvm.org/D104209

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 750839c57c162..a3d8637452978 100755
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -397,9 +397,13 @@ class AnnotatingParser {
   !CurrentToken->Next->HasUnescapedNewline &&
   !CurrentToken->Next->isTrailingComment())
 HasMultipleParametersOnALine = true;
+  bool ProbablyFunctionTypeLParen =
+  (CurrentToken->is(tok::l_paren) && CurrentToken->Next &&
+   CurrentToken->Next->isOneOf(tok::star, tok::amp, tok::caret));
   if ((CurrentToken->Previous->isOneOf(tok::kw_const, tok::kw_auto) ||
CurrentToken->Previous->isSimpleTypeSpecifier()) &&
-  !CurrentToken->isOneOf(tok::l_brace, tok::l_paren))
+  !(CurrentToken->is(tok::l_brace) ||
+(CurrentToken->is(tok::l_paren) && !ProbablyFunctionTypeLParen)))
 Contexts.back().IsExpression = false;
   if (CurrentToken->isOneOf(tok::semi, tok::colon)) {
 MightBeObjCForRangeLoop = false;

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 279f2b3119fc9..3df5d23a930f1 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -8707,6 +8707,11 @@ TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
   verifyFormat("void f() { f(float{1}, a * a); }");
   verifyFormat("void f() { f(float(1), a * a); }");
+
+  verifyFormat("f((void (*)(int))g);");
+  verifyFormat("f((void (&)(int))g);");
+  verifyFormat("f((void (^)(int))g);");
+
   // FIXME: Is there a way to make this work?
   // verifyIndependentOfContext("MACRO(A *a);");
   verifyFormat("MACRO(A );");



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 8fa56f7 - [clang-format] Prevent extraneous space insertion in bitshift operators

2021-05-04 Thread Krasimir Georgiev via cfe-commits

Author: Luis Penagos
Date: 2021-05-04T12:28:49+02:00
New Revision: 8fa56f7ededcbe28cbbb810b5d261b72ab0d8035

URL: 
https://github.com/llvm/llvm-project/commit/8fa56f7ededcbe28cbbb810b5d261b72ab0d8035
DIFF: 
https://github.com/llvm/llvm-project/commit/8fa56f7ededcbe28cbbb810b5d261b72ab0d8035.diff

LOG: [clang-format] Prevent extraneous space insertion in bitshift operators

This serves to augment the improvements made in 
https://reviews.llvm.org/D86581. It prevents clang-format from interpreting 
bitshift operators as template arguments in certain circumstances. This is an 
attempt at fixing https://bugs.llvm.org/show_bug.cgi?id=49868

Reviewed By: MyDeveloperDay, krasimir

Differential Revision: https://reviews.llvm.org/D100778

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 719bb3fdd0665..54b73d6e75bb6 100755
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -116,10 +116,17 @@ class AnnotatingParser {
 while (CurrentToken) {
   if (CurrentToken->is(tok::greater)) {
 // Try to do a better job at looking for ">>" within the condition of
-// a statement.
+// a statement. Conservatively insert spaces between consecutive ">"
+// tokens to prevent splitting right bitshift operators and potentially
+// altering program semantics. This check is overly conservative and
+// will prevent spaces from being inserted in select nested template
+// parameter cases, but should not alter program semantics.
 if (CurrentToken->Next && CurrentToken->Next->is(tok::greater) &&
 Left->ParentBracket != tok::less &&
-isKeywordWithCondition(*Line.First))
+(isKeywordWithCondition(*Line.First) ||
+ CurrentToken->getStartOfNonWhitespace() ==
+ 
CurrentToken->Next->getStartOfNonWhitespace().getLocWithOffset(
+ -1)))
   return false;
 Left->MatchingParen = CurrentToken;
 CurrentToken->MatchingParen = Left;

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 38b4c654f817a..1ba43e3eaf198 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -8007,6 +8007,8 @@ TEST_F(FormatTest, UnderstandsTemplateParameters) {
   verifyFormat("a = 1;", Style);
   verifyFormat("a >>= 1;", Style);
 
+  verifyFormat("test < a | b >> c;");
+  verifyFormat("test> c;");
   verifyFormat("test >> a >> b;");
   verifyFormat("test << a >> b;");
 



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 5987d7c - [clang-format] fix indent in alignChainedConditionals

2021-04-26 Thread Krasimir Georgiev via cfe-commits

Author: Krasimir Georgiev
Date: 2021-04-26T11:06:29+02:00
New Revision: 5987d7c59da5a7611036c2952f5a1f501d17ad48

URL: 
https://github.com/llvm/llvm-project/commit/5987d7c59da5a7611036c2952f5a1f501d17ad48
DIFF: 
https://github.com/llvm/llvm-project/commit/5987d7c59da5a7611036c2952f5a1f501d17ad48.diff

LOG: [clang-format] fix indent in alignChainedConditionals

Clang-format was indenting the lines following the `?` in the added test
case by +5 instead of +4. This only happens in a very specific
situation, where the `?` is followed by a multiline block comment, as in
the example. This fix addresses this without regressing any of the
existing tests.

Differential Revision: https://reviews.llvm.org/D101033

Added: 


Modified: 
clang/lib/Format/WhitespaceManager.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/WhitespaceManager.cpp 
b/clang/lib/Format/WhitespaceManager.cpp
index 6016f8d131c7..e78c5c4df586 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -778,12 +778,11 @@ void WhitespaceManager::alignChainedConditionals() {
 Changes, /*StartAt=*/0);
   } else {
 static auto AlignWrappedOperand = [](Change const ) {
-  auto Previous = C.Tok->getPreviousNonComment(); // Previous;
+  FormatToken *Previous = C.Tok->getPreviousNonComment();
   return C.NewlinesBefore && Previous && Previous->is(TT_ConditionalExpr) 
&&
- (Previous->is(tok::question) ||
-  (Previous->is(tok::colon) &&
-   (C.Tok->FakeLParens.size() == 0 ||
-C.Tok->FakeLParens.back() != prec::Conditional)));
+ (Previous->is(tok::colon) &&
+  (C.Tok->FakeLParens.size() == 0 ||
+   C.Tok->FakeLParens.back() != prec::Conditional));
 };
 // Ensure we keep alignment of wrapped operands with non-wrapped operands
 // Since we actually align the operators, the wrapped operands need the

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 5ae67d91323d..734ffed088a1 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -6459,6 +6459,30 @@ TEST_F(FormatTest, BreaksConditionalExpressions) {
"? cc :\n"
"  d;\n",
Style);
+
+  EXPECT_EQ(
+  "MMM = A ?\n"
+  "/*\n"
+  " */\n"
+  "function() {\n"
+  "  try {\n"
+  "return JJ(\n"
+  "pp);\n"
+  "  }\n"
+  "} :\n"
+  "function() {};",
+  format(
+  "MMM = A ?\n"
+  " /*\n"
+  "  */\n"
+  " function() {\n"
+  "  try {\n"
+  "return JJ(\n"
+  "pp);\n"
+  "  }\n"
+  "} :\n"
+  "function() {};",
+  getGoogleStyle(FormatStyle::LK_JavaScript)));
 }
 
 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) {



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] d9abcdd - [clang-format] Fix ObjC method indent after f7f9f94b

2021-03-25 Thread Krasimir Georgiev via cfe-commits

Author: Krasimir Georgiev
Date: 2021-03-25T10:52:08+01:00
New Revision: d9abcdd9f471ab0d986197e94498a5cf90aa12ef

URL: 
https://github.com/llvm/llvm-project/commit/d9abcdd9f471ab0d986197e94498a5cf90aa12ef
DIFF: 
https://github.com/llvm/llvm-project/commit/d9abcdd9f471ab0d986197e94498a5cf90aa12ef.diff

LOG: [clang-format] Fix ObjC method indent after f7f9f94b

Commit
https://github.com/llvm/llvm-project/commit/f7f9f94b2e2b4c714bac9036f6b73a3df42daaff
changed the indent of ObjC method arguments from +4 to +2, if the method
occurs after a block statement.  I believe this was unintentional and there
was insufficient ObjC test coverage to catch this.

Example: `clang-format -style=google test.mm`

before:
```
void a(int c) {
  if (c) {
f();
  }
  [
  e:^(fff ) {
f(S, c);
  }];
}
```

after:
```
void a(int c) {
  if (c) {
f();
  }
  [
e:^(fff ) {
  f(S, c);
}];
}
```

Differential Revision: https://reviews.llvm.org/D99063

Added: 


Modified: 
clang/lib/Format/UnwrappedLineParser.cpp
clang/unittests/Format/FormatTestObjC.cpp

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 1404d4a8eaeb..e424fcb34219 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -649,7 +649,6 @@ void UnwrappedLineParser::parseBlock(bool 
MustBeDeclaration, unsigned AddLevels,
 nextToken();
 
   Line->Level = InitialLevel;
-  FormatTok->setBlockKind(BK_Block);
 
   if (PPStartHash == PPEndHash) {
 Line->MatchingOpeningBlockLineIndex = OpeningLineIndex;

diff  --git a/clang/unittests/Format/FormatTestObjC.cpp 
b/clang/unittests/Format/FormatTestObjC.cpp
index c33f93bcf99d..aa27f6ecf93b 100644
--- a/clang/unittests/Format/FormatTestObjC.cpp
+++ b/clang/unittests/Format/FormatTestObjC.cpp
@@ -977,6 +977,19 @@ TEST_F(FormatTestObjC, FormatObjCMethodExpr) {
   "performSelectorOnMainThread:@selector(loadAccessories)\n"
   " withObject:nil\n"
   "  waitUntilDone:false];");
+
+  // The appropriate indentation is used after a block statement.
+  Style.ContinuationIndentWidth = 4;
+  verifyFormat(
+  "void a(int c) {\n"
+  "  if (c) {\n"
+  "f();\n"
+  "  }\n"
+  "  [\n"
+  "  e:^(fff ) {\n"
+  "f(S, c);\n"
+  "  }];\n"
+  "}");
 }
 
 TEST_F(FormatTestObjC, ObjCAt) {



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 587859d - clang-format: use `pb` as a canonical raw string delimiter for google style

2021-03-09 Thread Krasimir Georgiev via cfe-commits

Author: Krasimir Georgiev
Date: 2021-03-09T09:07:14+01:00
New Revision: 587859d977e88648bee1888dce5175ef827f212e

URL: 
https://github.com/llvm/llvm-project/commit/587859d977e88648bee1888dce5175ef827f212e
DIFF: 
https://github.com/llvm/llvm-project/commit/587859d977e88648bee1888dce5175ef827f212e.diff

LOG: clang-format: use `pb` as a canonical raw string delimiter for google style

This updates the canonical text proto raw string delimiter to `pb` for Google 
style, moving codebases towards a simpler and more consistent style.

Also updates a behavior where the canonical delimiter was not applied for raw 
strings with empty delimiters detected via well-known enclosing functions that 
expect a text proto, effectively making the canonical delimiter more viral. 
This feature is not widely used so this should be safe and more in line with 
promoting the canonicity of the canonical delimiter.

Reviewed By: sammccall

Differential Revision: https://reviews.llvm.org/D97688

Added: 


Modified: 
clang/lib/Format/ContinuationIndenter.cpp
clang/lib/Format/Format.cpp
clang/unittests/Format/FormatTestRawStrings.cpp

Removed: 




diff  --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index ffb328f7de13..cbf016f4b166 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -1651,7 +1651,7 @@ unsigned ContinuationIndenter::reformatRawStringLiteral(
   StringRef OldDelimiter = *getRawStringDelimiter(Current.TokenText);
   StringRef NewDelimiter =
   getCanonicalRawStringDelimiter(Style, RawStringStyle.Language);
-  if (NewDelimiter.empty() || OldDelimiter.empty())
+  if (NewDelimiter.empty())
 NewDelimiter = OldDelimiter;
   // The text of a raw string is between the leading 'R"delimiter(' and the
   // trailing 'delimiter)"'.

diff  --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 674f3e1220f7..120202caa3cd 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -1137,7 +1137,7 @@ FormatStyle getGoogleStyle(FormatStyle::LanguageKind 
Language) {
   "ParseTestProto",
   "ParsePartialTestProto",
   },
-  /*CanonicalDelimiter=*/"",
+  /*CanonicalDelimiter=*/"pb",
   /*BasedOnStyle=*/"google",
   },
   };

diff  --git a/clang/unittests/Format/FormatTestRawStrings.cpp 
b/clang/unittests/Format/FormatTestRawStrings.cpp
index 6310fe510fd3..6f9a0d650ba2 100644
--- a/clang/unittests/Format/FormatTestRawStrings.cpp
+++ b/clang/unittests/Format/FormatTestRawStrings.cpp
@@ -782,11 +782,16 @@ a = ParseTextProto(R"(key:value)");)test",
 }
 
 TEST_F(FormatTestRawStrings, UpdatesToCanonicalDelimiters) {
-  FormatStyle Style = getRawStringPbStyleWithColumns(25);
+  FormatStyle Style = getRawStringPbStyleWithColumns(35);
   Style.RawStringFormats[0].CanonicalDelimiter = "proto";
+  Style.RawStringFormats[0].EnclosingFunctions.push_back("PARSE_TEXT_PROTO");
+
   expect_eq(R"test(a = R"proto(key: value)proto";)test",
 format(R"test(a = R"pb(key:value)pb";)test", Style));
 
+  expect_eq(R"test(PARSE_TEXT_PROTO(R"proto(key: value)proto");)test",
+format(R"test(PARSE_TEXT_PROTO(R"(key:value)");)test", Style));
+
   // Don't update to canonical delimiter if it occurs as a raw string suffix in
   // the raw string content.
   expect_eq(R"test(a = R"pb(key: ")proto")pb";)test",



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 77b4841 - [clang-format] do not break before @tags in JS comments

2020-11-11 Thread Krasimir Georgiev via cfe-commits

Author: Krasimir Georgiev
Date: 2020-11-11T12:27:15+01:00
New Revision: 77b484116971337c9584fe101cdf1bca7f07f4dd

URL: 
https://github.com/llvm/llvm-project/commit/77b484116971337c9584fe101cdf1bca7f07f4dd
DIFF: 
https://github.com/llvm/llvm-project/commit/77b484116971337c9584fe101cdf1bca7f07f4dd.diff

LOG: [clang-format] do not break before @tags in JS comments

In JavaScript breaking before a `@tag` in a comment puts it on a new line, and
machinery that parses these comments will fail to understand such comments.

This adapts clang-format to not break before `@`. Similar functionality exists
for not breaking before `{`.

Reviewed By: mprobst

Differential Revision: https://reviews.llvm.org/D91078

Added: 


Modified: 
clang/lib/Format/BreakableToken.cpp
clang/unittests/Format/FormatTestJS.cpp

Removed: 




diff  --git a/clang/lib/Format/BreakableToken.cpp 
b/clang/lib/Format/BreakableToken.cpp
index c3853687c228..4975c89164a4 100644
--- a/clang/lib/Format/BreakableToken.cpp
+++ b/clang/lib/Format/BreakableToken.cpp
@@ -124,9 +124,10 @@ getCommentSplit(StringRef Text, unsigned 
ContentStartColumn,
   continue;
 }
 
-// Avoid ever breaking before a { in JavaScript.
+// Avoid ever breaking before a @tag or a { in JavaScript.
 if (Style.Language == FormatStyle::LK_JavaScript &&
-SpaceOffset + 1 < Text.size() && Text[SpaceOffset + 1] == '{') {
+SpaceOffset + 1 < Text.size() &&
+(Text[SpaceOffset + 1] == '{' || Text[SpaceOffset + 1] == '@')) {
   SpaceOffset = Text.find_last_of(Blanks, SpaceOffset);
   continue;
 }

diff  --git a/clang/unittests/Format/FormatTestJS.cpp 
b/clang/unittests/Format/FormatTestJS.cpp
index 84d76c67764a..8963c9f19024 100644
--- a/clang/unittests/Format/FormatTestJS.cpp
+++ b/clang/unittests/Format/FormatTestJS.cpp
@@ -187,22 +187,11 @@ TEST_F(FormatTestJS, JSDocComments) {
 format("/** @returns j */", getGoogleJSStyleWithColumns(20)));
 
   // Break a single line long jsdoc comment pragma.
-  EXPECT_EQ("/**\n"
-" * @returns {string} jsdoc line 12\n"
-" */",
-format("/** @returns {string} jsdoc line 12 */",
-   getGoogleJSStyleWithColumns(20)));
   EXPECT_EQ("/**\n"
 " * @returns {string}\n"
 " * jsdoc line 12\n"
 " */",
 format("/** @returns {string} jsdoc line 12 */",
-   getGoogleJSStyleWithColumns(25)));
-
-  EXPECT_EQ("/**\n"
-" * @returns {string} jsdoc line 12\n"
-" */",
-format("/** @returns {string} jsdoc line 12  */",
getGoogleJSStyleWithColumns(20)));
 
   // FIXME: this overcounts the */ as a continuation of the 12 when breaking.
@@ -2194,6 +2183,16 @@ TEST_F(FormatTestJS, JSDocAnnotations) {
  " */",
  getGoogleJSStyleWithColumns(ColumnLimit));
   }
+  // don't break before @tags
+  verifyFormat("/**\n"
+   " * This\n"
+   " * tag @param\n"
+   " * stays.\n"
+   " */",
+   "/**\n"
+   " * This tag @param stays.\n"
+   " */",
+   getGoogleJSStyleWithColumns(13));
   verifyFormat("/**\n"
" * @see http://very/very/long/url/is/long\n;
" */",



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 7b7170f - [clang-format] avoid introducing multiline comments

2020-11-09 Thread Krasimir Georgiev via cfe-commits

Author: Krasimir Georgiev
Date: 2020-11-09T15:29:09+01:00
New Revision: 7b7170fa5791a8fcf28418e6daa1ab7dd2126a25

URL: 
https://github.com/llvm/llvm-project/commit/7b7170fa5791a8fcf28418e6daa1ab7dd2126a25
DIFF: 
https://github.com/llvm/llvm-project/commit/7b7170fa5791a8fcf28418e6daa1ab7dd2126a25.diff

LOG: [clang-format] avoid introducing multiline comments

In C++ with -Werror=comment, multiline comments are not allowed.
clang-format could accidentally introduce multiline comments when reflowing.
This adapts clang-format to not introduce multiline comments by not allowing a
break after `\`. Note that this does not apply to comment lines that already are
multiline comments, such as comments in macros.

Reviewed By: sammccall

Differential Revision: https://reviews.llvm.org/D90949

Added: 


Modified: 
clang/lib/Format/BreakableToken.cpp
clang/unittests/Format/FormatTestComments.cpp

Removed: 




diff  --git a/clang/lib/Format/BreakableToken.cpp 
b/clang/lib/Format/BreakableToken.cpp
index 2ef1540a7f82..c3853687c228 100644
--- a/clang/lib/Format/BreakableToken.cpp
+++ b/clang/lib/Format/BreakableToken.cpp
@@ -101,17 +101,37 @@ getCommentSplit(StringRef Text, unsigned 
ContentStartColumn,
   StringRef::size_type SpaceOffset = Text.find_last_of(Blanks, MaxSplitBytes);
 
   static const auto kNumberedListRegexp = llvm::Regex("^[1-9][0-9]?\\.");
+  // Some spaces are unacceptable to break on, rewind past them.
   while (SpaceOffset != StringRef::npos) {
+// If a line-comment ends with `\`, the next line continues the comment,
+// whether or not it starts with `//`. This is confusing and triggers
+// -Wcomment.
+// Avoid introducing multiline comments by not allowing a break right
+// after '\'.
+if (Style.isCpp()) {
+  StringRef::size_type LastNonBlank =
+  Text.find_last_not_of(Blanks, SpaceOffset);
+  if (LastNonBlank != StringRef::npos && Text[LastNonBlank] == '\\') {
+SpaceOffset = Text.find_last_of(Blanks, LastNonBlank);
+continue;
+  }
+}
+
 // Do not split before a number followed by a dot: this would be 
interpreted
 // as a numbered list, which would prevent re-flowing in subsequent passes.
-if (kNumberedListRegexp.match(Text.substr(SpaceOffset).ltrim(Blanks)))
+if (kNumberedListRegexp.match(Text.substr(SpaceOffset).ltrim(Blanks))) {
   SpaceOffset = Text.find_last_of(Blanks, SpaceOffset);
+  continue;
+}
+
 // Avoid ever breaking before a { in JavaScript.
-else if (Style.Language == FormatStyle::LK_JavaScript &&
- SpaceOffset + 1 < Text.size() && Text[SpaceOffset + 1] == '{')
+if (Style.Language == FormatStyle::LK_JavaScript &&
+SpaceOffset + 1 < Text.size() && Text[SpaceOffset + 1] == '{') {
   SpaceOffset = Text.find_last_of(Blanks, SpaceOffset);
-else
-  break;
+  continue;
+}
+
+break;
   }
 
   if (SpaceOffset == StringRef::npos ||

diff  --git a/clang/unittests/Format/FormatTestComments.cpp 
b/clang/unittests/Format/FormatTestComments.cpp
index 95afb17114a2..27dfe71367b3 100644
--- a/clang/unittests/Format/FormatTestComments.cpp
+++ b/clang/unittests/Format/FormatTestComments.cpp
@@ -745,6 +745,24 @@ TEST_F(FormatTestComments, 
DontSplitLineCommentsWithEscapedNewlines) {
getLLVMStyleWithColumns(49)));
 }
 
+TEST_F(FormatTestComments, DontIntroduceMultilineComments) {
+  // Avoid introducing a multiline comment by breaking after `\`.
+  for (int ColumnLimit = 15; ColumnLimit <= 17; ++ColumnLimit) {
+EXPECT_EQ(
+"// aa\n"
+"// \\ bb",
+format("// aa \\ bb", getLLVMStyleWithColumns(ColumnLimit)));
+EXPECT_EQ(
+"// a\n"
+"// \\  bb",
+format("// a \\  bb", getLLVMStyleWithColumns(ColumnLimit)));
+EXPECT_EQ(
+"// a\n"
+"// \\  \\ bb",
+format("// a \\  \\ bb", 
getLLVMStyleWithColumns(ColumnLimit)));
+  }
+}
+
 TEST_F(FormatTestComments, DontSplitLineCommentsWithPragmas) {
   FormatStyle Pragmas = getLLVMStyleWithColumns(30);
   Pragmas.CommentPragmas = "^ IWYU pragma:";



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 2dbcbd3 - [clang-format] do not break before { in JS comments

2020-11-06 Thread Krasimir Georgiev via cfe-commits

Author: Krasimir Georgiev
Date: 2020-11-06T10:34:10+01:00
New Revision: 2dbcbd357d1da1adf9c512d150e68424faa46d75

URL: 
https://github.com/llvm/llvm-project/commit/2dbcbd357d1da1adf9c512d150e68424faa46d75
DIFF: 
https://github.com/llvm/llvm-project/commit/2dbcbd357d1da1adf9c512d150e68424faa46d75.diff

LOG: [clang-format] do not break before { in JS comments

In JavaScript some @tags can be followed by `{`, and machinery that parses
these comments will fail to understand the comment if followed by a line break.

clang-format already handles this case by not breaking before `{` in comments.
However this was not working in cases when the column limit falls within `@tag`
or between `@tag` and `{`. This adapts clang-format for this case.

Reviewed By: mprobst

Differential Revision: https://reviews.llvm.org/D90908

Added: 


Modified: 
clang/lib/Format/BreakableToken.cpp
clang/unittests/Format/FormatTestJS.cpp

Removed: 




diff  --git a/clang/lib/Format/BreakableToken.cpp 
b/clang/lib/Format/BreakableToken.cpp
index 15fbe3b6515d..2ef1540a7f82 100644
--- a/clang/lib/Format/BreakableToken.cpp
+++ b/clang/lib/Format/BreakableToken.cpp
@@ -86,6 +86,18 @@ getCommentSplit(StringRef Text, unsigned ContentStartColumn,
 MaxSplitBytes += BytesInChar;
   }
 
+  // In JavaScript, some @tags can be followed by {, and machinery that parses
+  // these comments will fail to understand the comment if followed by a line
+  // break. So avoid ever breaking before a {.
+  if (Style.Language == FormatStyle::LK_JavaScript) {
+StringRef::size_type SpaceOffset =
+Text.find_first_of(Blanks, MaxSplitBytes);
+if (SpaceOffset != StringRef::npos && SpaceOffset + 1 < Text.size() &&
+Text[SpaceOffset + 1] == '{') {
+  MaxSplitBytes = SpaceOffset + 1;
+}
+  }
+
   StringRef::size_type SpaceOffset = Text.find_last_of(Blanks, MaxSplitBytes);
 
   static const auto kNumberedListRegexp = llvm::Regex("^[1-9][0-9]?\\.");
@@ -94,9 +106,7 @@ getCommentSplit(StringRef Text, unsigned ContentStartColumn,
 // as a numbered list, which would prevent re-flowing in subsequent passes.
 if (kNumberedListRegexp.match(Text.substr(SpaceOffset).ltrim(Blanks)))
   SpaceOffset = Text.find_last_of(Blanks, SpaceOffset);
-// In JavaScript, some @tags can be followed by {, and machinery that 
parses
-// these comments will fail to understand the comment if followed by a line
-// break. So avoid ever breaking before a {.
+// Avoid ever breaking before a { in JavaScript.
 else if (Style.Language == FormatStyle::LK_JavaScript &&
  SpaceOffset + 1 < Text.size() && Text[SpaceOffset + 1] == '{')
   SpaceOffset = Text.find_last_of(Blanks, SpaceOffset);

diff  --git a/clang/unittests/Format/FormatTestJS.cpp 
b/clang/unittests/Format/FormatTestJS.cpp
index da26a9b67278..d140fe581f2a 100644
--- a/clang/unittests/Format/FormatTestJS.cpp
+++ b/clang/unittests/Format/FormatTestJS.cpp
@@ -2184,6 +2184,16 @@ TEST_F(FormatTestJS, JSDocAnnotations) {
" * @lala {lala {lalala\n"
" */\n",
getGoogleJSStyleWithColumns(20));
+  // cases where '{' is around the column limit
+  for (int ColumnLimit = 6; ColumnLimit < 13; ++ColumnLimit) {
+verifyFormat("/**\n"
+ " * @param {type}\n"
+ " */",
+ "/**\n"
+ " * @param {type}\n"
+ " */",
+ getGoogleJSStyleWithColumns(ColumnLimit));
+  }
   verifyFormat("/**\n"
" * @see http://very/very/long/url/is/long\n;
" */",



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] df00267 - clang-format: Add a consumer to diagnostics engine

2020-10-29 Thread Krasimir Georgiev via cfe-commits

Author: Krasimir Georgiev
Date: 2020-10-29T11:28:27+01:00
New Revision: df00267f1fdb0b098dc42f1caa8a59b29c8e0e5f

URL: 
https://github.com/llvm/llvm-project/commit/df00267f1fdb0b098dc42f1caa8a59b29c8e0e5f
DIFF: 
https://github.com/llvm/llvm-project/commit/df00267f1fdb0b098dc42f1caa8a59b29c8e0e5f.diff

LOG: clang-format: Add a consumer to diagnostics engine

Contributed by dmikis (Kirill Dmitrenko)!

Otherwise problems like trying to format readonly file in-place led to crashes.

I've added reviewers by looking at `git blame` and other reviews to the changed 
file, so may have missed someone.

Reviewed By: krasimir

Differential Revision: https://reviews.llvm.org/D90121

Added: 


Modified: 
clang/tools/clang-format/CMakeLists.txt
clang/tools/clang-format/ClangFormat.cpp

Removed: 




diff  --git a/clang/tools/clang-format/CMakeLists.txt 
b/clang/tools/clang-format/CMakeLists.txt
index 35ecdb11253c..28ac4fb5913e 100644
--- a/clang/tools/clang-format/CMakeLists.txt
+++ b/clang/tools/clang-format/CMakeLists.txt
@@ -7,6 +7,7 @@ add_clang_tool(clang-format
 set(CLANG_FORMAT_LIB_DEPS
   clangBasic
   clangFormat
+  clangFrontend
   clangRewrite
   clangToolingCore
   )

diff  --git a/clang/tools/clang-format/ClangFormat.cpp 
b/clang/tools/clang-format/ClangFormat.cpp
index 3a7247deab46..d7b768329bcc 100644
--- a/clang/tools/clang-format/ClangFormat.cpp
+++ b/clang/tools/clang-format/ClangFormat.cpp
@@ -18,6 +18,7 @@
 #include "clang/Basic/SourceManager.h"
 #include "clang/Basic/Version.h"
 #include "clang/Format/Format.h"
+#include "clang/Frontend/TextDiagnosticPrinter.h"
 #include "clang/Rewrite/Core/Rewriter.h"
 #include "llvm/Support/CommandLine.h"
 #include "llvm/Support/FileSystem.h"
@@ -423,9 +424,11 @@ static bool format(StringRef FileName) {
 IntrusiveRefCntPtr InMemoryFileSystem(
 new llvm::vfs::InMemoryFileSystem);
 FileManager Files(FileSystemOptions(), InMemoryFileSystem);
+IntrusiveRefCntPtr DiagOpts(new DiagnosticOptions());
+TextDiagnosticPrinter DiagnosticsConsumer(errs(), &*DiagOpts);
 DiagnosticsEngine Diagnostics(
-IntrusiveRefCntPtr(new DiagnosticIDs),
-new DiagnosticOptions);
+IntrusiveRefCntPtr(new DiagnosticIDs), &*DiagOpts,
+, false);
 SourceManager Sources(Diagnostics, Files);
 FileID ID = createInMemoryFile(AssumedFileName, Code.get(), Sources, Files,
InMemoryFileSystem.get());



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 0fad648 - [clang-format] restore indent in conditionals when AlignOperands is DontAlign

2020-06-24 Thread Krasimir Georgiev via cfe-commits

Author: Krasimir Georgiev
Date: 2020-06-24T13:11:18+02:00
New Revision: 0fad648b65b99b68040fa26c5da9c0bec5b0aa1d

URL: 
https://github.com/llvm/llvm-project/commit/0fad648b65b99b68040fa26c5da9c0bec5b0aa1d
DIFF: 
https://github.com/llvm/llvm-project/commit/0fad648b65b99b68040fa26c5da9c0bec5b0aa1d.diff

LOG: [clang-format] restore indent in conditionals when AlignOperands is 
DontAlign

Summary:
After D50078, we're experiencing unexpected un-indent using a style combining 
`AlignOperands: DontAlign` with `BreakBeforeTernaryOperators: false`, such as 
Google's JavaScript style:
```
% bin/clang-format -style=google ~/test.js
aaa =  ? cc() :
dd ? ee :
 f;
```
The issue lies with the interaction of `AlignOperands: DontAlign` and the 
edited code section in ContinuationIndenter.cpp, which de-dents the intent by 
`Style.ContinuationIndentWidth`. From [[ 
https://github.com/llvm/llvm-project/blob/ac3e5c4d93fbe7fb2db3c745c721aff41cc1b851/clang/include/clang/Format/Format.h#L170
 | the documentation ]] of AlignOperands: DontAlign:
> The wrapped lines are indented `ContinuationIndentWidth` spaces from the 
> start of the line.
So the de-dent effectively erases the necessary `ContinuationIndentWidth` in 
that case.

This patch restores the `AlignOperands: DontAlign` behavior, producing:
```
% bin/clang-format -style=google ~/test.js
aaa =  ? cc() :
dd ? ee :
 f;
```

Reviewers: sammccall

Reviewed By: sammccall

Subscribers: cfe-commits

Tags: #clang

Differential Revision: https://reviews.llvm.org/D82199

Added: 


Modified: 
clang/lib/Format/ContinuationIndenter.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index 2ac43b6cfa4b..b1497651a8fe 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -1041,8 +1041,10 @@ unsigned ContinuationIndenter::getNewLineColumn(const 
LineState ) {
   //* not remove the 'lead' ContinuationIndentWidth
   //* always un-indent by the operator when
   //BreakBeforeTernaryOperators=true
-  unsigned Indent =
-  State.Stack.back().Indent - Style.ContinuationIndentWidth;
+  unsigned Indent = State.Stack.back().Indent;
+  if (Style.AlignOperands != FormatStyle::OAS_DontAlign) {
+Indent -= Style.ContinuationIndentWidth;
+  }
   if (Style.BreakBeforeTernaryOperators &&
   State.Stack.back().UnindentOperator)
 Indent -= 2;

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index dce71b0f0692..beaa68a24617 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -6281,6 +6281,17 @@ TEST_F(FormatTest, BreaksConditionalExpressions) {
"   : bbb ? \n"
" : ;",
Style);
+
+  Style.AlignOperands = FormatStyle::OAS_DontAlign;
+  Style.BreakBeforeTernaryOperators = false;
+  // FIXME: Aligning the question marks is weird given DontAlign.
+  // Consider disabling this alignment in this case. Also check whether this
+  // will render the adjustment from https://reviews.llvm.org/D82199
+  // unnecessary.
+  verifyFormat("int x = aaa ? aa :\n"
+   "? cc :\n"
+   "  d;\n",
+   Style);
 }
 
 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) {



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 0574030 - [clang-format] only parse C# generic type constraints in C#

2020-03-30 Thread Krasimir Georgiev via cfe-commits

Author: Krasimir Georgiev
Date: 2020-03-30T13:13:07+02:00
New Revision: 0574030c01615d4ce26de0d9b0d64292ab3eac9b

URL: 
https://github.com/llvm/llvm-project/commit/0574030c01615d4ce26de0d9b0d64292ab3eac9b
DIFF: 
https://github.com/llvm/llvm-project/commit/0574030c01615d4ce26de0d9b0d64292ab3eac9b.diff

LOG: [clang-format] only parse C# generic type constraints in C#

Commit "[clang-format] Handle C# generic type constraints",
https://github.com/llvm/llvm-project/commit/dcbcec4822f47ec5b638dd9c20dcebd464569dae
regressed the formatting of code containing `where` as an identifier in other
languages.

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 8a1e247463d5..8f40fc7bdcb6 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1047,7 +1047,7 @@ class AnnotatingParser {
Keywords.kw___has_include_next)) {
 parseHasInclude();
   }
-  if (Tok->is(Keywords.kw_where) && Tok->Next &&
+  if (Style.isCSharp() && Tok->is(Keywords.kw_where) && Tok->Next &&
   Tok->Next->isNot(tok::l_paren)) {
 Tok->Type = TT_CSharpGenericTypeConstraint;
 parseCSharpGenericTypeConstraint();

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index 17b8e070c36a..f5e0bab1cb31 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -709,6 +709,14 @@ class ItemFactory
   IAnotherInterface,
   IAnotherInterfaceStill {})",
Style);
+
+  // In other languages `where` can be used as a normal identifier.
+  // This example is in C++!
+  verifyFormat(R"(//
+class A {
+  int f(int where) {}
+};)",
+   getGoogleStyle(FormatStyle::LK_Cpp));
 }
 
 } // namespace format



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 36c2ab8 - [clang-format] do not insert spaces around inline asm symbolic names

2020-03-05 Thread Krasimir Georgiev via cfe-commits

Author: Krasimir Georgiev
Date: 2020-03-05T14:17:21+01:00
New Revision: 36c2ab8d04cd9ff2e50cffa1ca6b3de00e4faa81

URL: 
https://github.com/llvm/llvm-project/commit/36c2ab8d04cd9ff2e50cffa1ca6b3de00e4faa81
DIFF: 
https://github.com/llvm/llvm-project/commit/36c2ab8d04cd9ff2e50cffa1ca6b3de00e4faa81.diff

LOG: [clang-format] do not insert spaces around inline asm symbolic names

Summary:
Fixes https://bugs.llvm.org/show_bug.cgi?id=45108.

The `[` in such cases was mis-annotated as an `TT_ArrayInitializerLSquare`.

Reviewers: hans

Reviewed By: hans

Subscribers: cfe-commits

Tags: #clang

Differential Revision: https://reviews.llvm.org/D75675

Added: 


Modified: 
clang/lib/Format/FormatToken.h
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index d0d08e470e6c..072e1ad565c2 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -54,6 +54,7 @@ namespace format {
   TYPE(InheritanceComma)   
\
   TYPE(InlineASMBrace) 
\
   TYPE(InlineASMColon) 
\
+  TYPE(InlineASMSymbolicNameLSquare)   
\
   TYPE(JavaAnnotation) 
\
   TYPE(JsComputedPropertyName) 
\
   TYPE(JsExponentiation)   
\

diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index e491de85babd..2673dacfff13 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -499,6 +499,8 @@ class AnnotatingParser {
 } else if (Left->is(TT_Unknown)) {
   if (StartsObjCMethodExpr) {
 Left->Type = TT_ObjCMethodExpr;
+  } else if (InsideInlineASM) {
+Left->Type = TT_InlineASMSymbolicNameLSquare;
   } else if (IsCpp11AttributeSpecifier) {
 Left->Type = TT_AttributeSquare;
   } else if (Style.Language == FormatStyle::LK_JavaScript && Parent &&

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index f00c980cb715..cb052ecaf111 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -15127,6 +15127,30 @@ TEST_F(FormatTest, GuessLanguageWithCaret) {
   guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);"));
 }
 
+TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) {
+  // ASM symbolic names are identifiers that must be surrounded by [] without
+  // space in between:
+  // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands
+
+  // Example from https://bugs.llvm.org/show_bug.cgi?id=45108.
+  verifyFormat(R"(//
+asm volatile("mrs %x[result], FPCR" : [result] "=r"(result));
+)");
+
+  // A list of several ASM symbolic names.
+  verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)");
+
+  // ASM symbolic names in inline ASM with inputs and outputs.
+  verifyFormat(R"(//
+asm("cmoveq %1, %2, %[result]"
+: [result] "=r"(result)
+: "r"(test), "r"(new), "[result]"(old));
+)");
+
+  // ASM symbolic names in inline ASM with no outputs.
+  verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)");
+}
+
 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) {
   EXPECT_EQ(FormatStyle::LK_Cpp,
 guessLanguage("foo.h", "void f() {\n"



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 36a8f7f - [clang-format] Handle escaped " in C# string-literals

2020-01-27 Thread Krasimir Georgiev via cfe-commits

Author: Krasimir Georgiev
Date: 2020-01-27T12:57:20+01:00
New Revision: 36a8f7f6d8f5a9620b1a091e54abacb517ecfbba

URL: 
https://github.com/llvm/llvm-project/commit/36a8f7f6d8f5a9620b1a091e54abacb517ecfbba
DIFF: 
https://github.com/llvm/llvm-project/commit/36a8f7f6d8f5a9620b1a091e54abacb517ecfbba.diff

LOG: [clang-format] Handle escaped " in C# string-literals

Reviewers: krasimir

Reviewed By: krasimir

Subscribers: klimek, MyDeveloperDay

Tags: #clang-format

Differential Revision: https://reviews.llvm.org/D73353

Added: 


Modified: 
clang/lib/Format/FormatTokenLexer.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/FormatTokenLexer.cpp 
b/clang/lib/Format/FormatTokenLexer.cpp
index 9c9fee2b0c32..d8dfe17fb89c 100644
--- a/clang/lib/Format/FormatTokenLexer.cpp
+++ b/clang/lib/Format/FormatTokenLexer.cpp
@@ -184,15 +184,33 @@ bool FormatTokenLexer::tryMergeJSPrivateIdentifier() {
 bool FormatTokenLexer::tryMergeCSharpVerbatimStringLiteral() {
   if (Tokens.size() < 2)
 return false;
-  auto  = *(Tokens.end() - 2);
+
   auto  = *(Tokens.end() - 1);
+  if (!String->is(tok::string_literal))
+return false;
+
+  // verbatim strings could contain "" which C# sees as an escaped ".
+  // @"""Hello""" will have been tokenized as @"" "Hello" "" and needs
+  // merging into a single string literal.
+  auto  = *(Tokens.end() - 2);
+  if (CSharpStringLiteral->Type == TT_CSharpStringLiteral &&
+  (CSharpStringLiteral->TokenText.startswith(R"(@")") ||
+   CSharpStringLiteral->TokenText.startswith(R"($@")"))) {
+CSharpStringLiteral->TokenText = StringRef(
+CSharpStringLiteral->TokenText.begin(),
+String->TokenText.end() - CSharpStringLiteral->TokenText.begin());
+CSharpStringLiteral->ColumnWidth += String->ColumnWidth;
+Tokens.erase(Tokens.end() - 1);
+return true;
+  }
+
+  auto  = *(Tokens.end() - 2);
 
-  // Look for $"aa" @"aa".
-  if (!(At->is(tok::at) || At->TokenText == "$") ||
-  !String->is(tok::string_literal))
+  // Look for @"aa" or $"aa".
+  if (!(At->is(tok::at) || At->TokenText == "$"))
 return false;
 
-  if (Tokens.size() >= 2 && At->is(tok::at)) {
+  if (Tokens.size() > 2 && At->is(tok::at)) {
 auto  = *(Tokens.end() - 3);
 if (Dollar->TokenText == "$") {
   // This looks like $@"a" so we need to combine all 3 tokens.

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index 90d05ad679a7..f777d319ea40 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -409,5 +409,13 @@ TEST_F(FormatTestCSharp, CSharpSpaceAfterCStyleCast) {
   verifyFormat("(int) x / y;", Style);
 }
 
+TEST_F(FormatTestCSharp, CSharpEscapedQuotesInVerbatimStrings) {
+  FormatStyle Style = getGoogleStyle(FormatStyle::LK_CSharp);
+
+  verifyFormat(R"(string str = @)", Style);
+  verifyFormat(R"(string str = @"""Hello world""")", Style);
+  verifyFormat(R"(string str = $@"""Hello {friend}""")", Style);
+}
+
 } // namespace format
 } // end namespace clang



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 1e0174a - Treat C# `using` as a control statement

2020-01-23 Thread Krasimir Georgiev via cfe-commits

Author: Krasimir Georgiev
Date: 2020-01-23T13:19:55+01:00
New Revision: 1e0174a93cfd364bffd12abc8f0148509d0d0f75

URL: 
https://github.com/llvm/llvm-project/commit/1e0174a93cfd364bffd12abc8f0148509d0d0f75
DIFF: 
https://github.com/llvm/llvm-project/commit/1e0174a93cfd364bffd12abc8f0148509d0d0f75.diff

LOG: Treat C# `using` as a control statement

Contributed by jbcoe!

Summary: Unless SpaceBeforeParensOptions is set to SBPO_Never, a space will be 
put between `using` and `(` in C# code.

Reviewers: klimek, MyDeveloperDay, krasimir

Reviewed By: krasimir

Subscribers: MyDeveloperDay, cfe-commits

Tags: #clang-format, #clang

Differential Revision: https://reviews.llvm.org/D72144

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 7dbde9a8d6a8..05b1db2a878d 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2869,7 +2869,8 @@ bool TokenAnnotator::spaceRequiredBefore(const 
AnnotatedLine ,
 // space between keywords and paren e.g. "using ("
 if (Right.is(tok::l_paren))
   if (Left.is(tok::kw_using))
-return spaceRequiredBeforeParens(Left);
+return Style.SpaceBeforeParens == FormatStyle::SBPO_ControlStatements 
||
+   spaceRequiredBeforeParens(Right);
   } else if (Style.Language == FormatStyle::LK_JavaScript) {
 if (Left.is(TT_JsFatArrow))
   return true;

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index 95b14d0f0aa4..90d05ad679a7 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -235,20 +235,46 @@ TEST_F(FormatTestCSharp, CSharpUsing) {
   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
   verifyFormat("public void foo () {\n"
"  using (StreamWriter sw = new StreamWriter (filenameA)) {}\n"
+   "  using () {}\n"
"}",
Style);
 
+  // Ensure clang-format affects top-level snippets correctly.
   verifyFormat("using (StreamWriter sw = new StreamWriter (filenameB)) {}",
Style);
 
   Style.SpaceBeforeParens = FormatStyle::SBPO_Never;
   verifyFormat("public void foo() {\n"
"  using(StreamWriter sw = new StreamWriter(filenameB)) {}\n"
+   "  using() {}\n"
"}",
Style);
 
+  // Ensure clang-format affects top-level snippets correctly.
   verifyFormat("using(StreamWriter sw = new StreamWriter(filenameB)) {}",
Style);
+
+  Style.SpaceBeforeParens = FormatStyle::SBPO_ControlStatements;
+  verifyFormat("public void foo() {\n"
+   "  using (StreamWriter sw = new StreamWriter(filenameA)) {}\n"
+   "  using () {}\n"
+   "}",
+   Style);
+
+  // Ensure clang-format affects top-level snippets correctly.
+  verifyFormat("using (StreamWriter sw = new StreamWriter(filenameB)) {}",
+   Style);
+
+  Style.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses;
+  verifyFormat("public void foo() {\n"
+   "  using (StreamWriter sw = new StreamWriter (filenameA)) {}\n"
+   "  using() {}\n"
+   "}",
+   Style);
+
+  // Ensure clang-format affects top-level snippets correctly.
+  verifyFormat("using (StreamWriter sw = new StreamWriter (filenameB)) {}",
+   Style);
 }
 
 TEST_F(FormatTestCSharp, CSharpRegions) {



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 33463cf - clang-format: fix spacing in `operator const char*()`

2020-01-17 Thread Krasimir Georgiev via cfe-commits

Author: Krasimir Georgiev
Date: 2020-01-17T13:33:41+01:00
New Revision: 33463cfba2be7c8d6c08e666123cc34f114a1f3e

URL: 
https://github.com/llvm/llvm-project/commit/33463cfba2be7c8d6c08e666123cc34f114a1f3e
DIFF: 
https://github.com/llvm/llvm-project/commit/33463cfba2be7c8d6c08e666123cc34f114a1f3e.diff

LOG: clang-format: fix spacing in `operator const char*()`

Summary:
Revision a75f8d98d7ac9e557b238a229a9a2647c71feed1 fixed spacing for operators,
but caused the const and non-const versions to diverge:
```
// With Style.PointerAlignment = FormatStyle::PAS_Left:

struct A {
  operator char*() { return ""; }
  operator const char *() const { return ""; }
};

```
The code was checking if the type specifier was directly preceded by `operator`.
However there could be comments and `const/volatile` in between.

Reviewers: mprobst

Reviewed By: mprobst

Subscribers: cfe-commits

Tags: #clang

Differential Revision: https://reviews.llvm.org/D72911

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index d5d394e61926..21a2184bf1d8 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2707,10 +2707,17 @@ bool TokenAnnotator::spaceRequiredBetween(const 
AnnotatedLine ,
 return false;
   if (Right.isOneOf(tok::star, tok::amp, tok::ampamp) &&
   (Left.is(tok::identifier) || Left.isSimpleTypeSpecifier()) &&
-  Left.Previous && Left.Previous->is(tok::kw_operator))
-// Space between the type and the *
-// operator void*(), operator char*(), operator Foo*() dependant
-// on PointerAlignment style.
+  // Space between the type and the * in:
+  //   operator void*()
+  //   operator char*()
+  //   operator /*comment*/ const char*()
+  //   operator volatile /*comment*/ char*()
+  //   operator Foo*()
+  // dependent on PointerAlignment style.
+  Left.Previous &&
+  (Left.Previous->endsSequence(tok::kw_operator) ||
+   Left.Previous->endsSequence(tok::kw_const, tok::kw_operator) ||
+   Left.Previous->endsSequence(tok::kw_volatile, tok::kw_operator)))
 return (Style.PointerAlignment != FormatStyle::PAS_Left);
   const auto SpaceRequiredForArrayInitializerLSquare =
   [](const FormatToken , const FormatStyle ) {

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 2d67b9759d7f..d689658f99b6 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -15007,6 +15007,9 @@ TEST_F(FormatTest, OperatorSpacing) {
   Style.PointerAlignment = FormatStyle::PAS_Left;
   verifyFormat("Foo::operator*();", Style);
   verifyFormat("Foo::operator void*();", Style);
+  verifyFormat("Foo::operator/*comment*/ void*();", Style);
+  verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style);
+  verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style);
   verifyFormat("Foo::operator()(void*);", Style);
   verifyFormat("Foo::operator*(void*);", Style);
   verifyFormat("Foo::operator*();", Style);
@@ -15014,6 +15017,9 @@ TEST_F(FormatTest, OperatorSpacing) {
 
   verifyFormat("Foo::operator&();", Style);
   verifyFormat("Foo::operator void&();", Style);
+  verifyFormat("Foo::operator/*comment*/ void&();", Style);
+  verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style);
+  verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style);
   verifyFormat("Foo::operator()(void&);", Style);
   verifyFormat("Foo::operator&(void&);", Style);
   verifyFormat("Foo::operator&();", Style);
@@ -15021,6 +15027,9 @@ TEST_F(FormatTest, OperatorSpacing) {
 
   verifyFormat("Foo::operator&&();", Style);
   verifyFormat("Foo::operator void&&();", Style);
+  verifyFormat("Foo::operator/*comment*/ void&&();", Style);
+  verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style);
+  verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style);
   verifyFormat("Foo::operator()(void&&);", Style);
   verifyFormat("Foo::operator&&(void&&);", Style);
   verifyFormat("Foo::operator&&();", Style);



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r375247 - [clang-format] fix regression recognizing casts in Obj-C calls

2019-10-18 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Fri Oct 18 08:21:06 2019
New Revision: 375247

URL: http://llvm.org/viewvc/llvm-project?rev=375247=rev
Log:
[clang-format] fix regression recognizing casts in Obj-C calls

Summary:
r373922 added checks for a few tokens that, following an `)` make it
unlikely that the `)` is the closing paren of a cast expression. The
specific check for `tok::l_square` there introduced a regression for
casts of Obj-C calls, like:
```
(cast)[func arg]
```
From the tests added in r373922, I believe the `tok::l_square` case is added to
capture the case where a non-cast `)` is directly followed by an
attribute specifier, like:
```
int f(int x) [[noreturn]];
```

I've specialized the code to look for such attribute specifier instead
of `tok::l_square` in general. Also, I added a regression test and moved
the test cases added in r373922 to an already existing place documenting
other instances of historically misidentified casts.

Reviewers: MyDeveloperDay

Reviewed By: MyDeveloperDay

Subscribers: cfe-commits

Tags: #clang

Differential Revision: https://reviews.llvm.org/D69164

Modified:
cfe/trunk/lib/Format/TokenAnnotator.cpp
cfe/trunk/unittests/Format/FormatTest.cpp

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=375247=375246=375247=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Fri Oct 18 08:21:06 2019
@@ -1607,8 +1607,9 @@ private:
 // Functions which end with decorations like volatile, noexcept are 
unlikely
 // to be casts.
 if (Tok.Next->isOneOf(tok::kw_noexcept, tok::kw_volatile, tok::kw_const,
-  tok::kw_throw, tok::l_square, tok::arrow,
-  Keywords.kw_override, Keywords.kw_final))
+  tok::kw_throw, tok::arrow, Keywords.kw_override,
+  Keywords.kw_final) ||
+isCpp11AttributeSpecifier(*Tok.Next))
   return false;
 
 // As Java has no function types, a "(" after the ")" likely means that 
this

Modified: cfe/trunk/unittests/Format/FormatTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTest.cpp?rev=375247=375246=375247=diff
==
--- cfe/trunk/unittests/Format/FormatTest.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTest.cpp Fri Oct 18 08:21:06 2019
@@ -7541,6 +7541,8 @@ TEST_F(FormatTest, FormatsCasts) {
   verifyFormat("my_int a = (ns::my_int)-2;");
   verifyFormat("case (my_int)ONE:");
   verifyFormat("auto x = (X)this;");
+  // Casts in Obj-C style calls used to not be recognized as such.
+  verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle());
 
   // FIXME: single value wrapped with paren will be treated as cast.
   verifyFormat("void f(int i = (kValue)*kMask) {}");
@@ -7581,6 +7583,29 @@ TEST_F(FormatTest, FormatsCasts) {
   verifyFormat("int a = alignof(int *) + b;", getGoogleStyle());
   verifyFormat("bool b = f(g) && c;");
   verifyFormat("typedef void (*f)(int i) func;");
+  verifyFormat("void operator++(int) noexcept;");
+  verifyFormat("void operator++(int &) noexcept;");
+  verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t 
"
+   "&) noexcept;");
+  verifyFormat(
+  "void operator delete(std::size_t, const std::nothrow_t &) noexcept;");
+  verifyFormat("void operator delete(const std::nothrow_t &) noexcept;");
+  verifyFormat("void operator delete(std::nothrow_t &) noexcept;");
+  verifyFormat("void operator delete(nothrow_t &) noexcept;");
+  verifyFormat("void operator delete(foo &) noexcept;");
+  verifyFormat("void operator delete(foo) noexcept;");
+  verifyFormat("void operator delete(int) noexcept;");
+  verifyFormat("void operator delete(int &) noexcept;");
+  verifyFormat("void operator delete(int &) volatile noexcept;");
+  verifyFormat("void operator delete(int &) const");
+  verifyFormat("void operator delete(int &) = default");
+  verifyFormat("void operator delete(int &) = delete");
+  verifyFormat("void operator delete(int &) [[noreturn]]");
+  verifyFormat("void operator delete(int &) throw();");
+  verifyFormat("void operator delete(int &) throw(int);");
+  verifyFormat("auto operator delete(int &) -> int;");
+  verifyFormat("auto operator delete(int &) override");
+  verifyFormat("auto operator delete(int &) final");
 
   verifyFormat(" *foo = (a 
*)\n"
"bbb;");
@@ -14696,33 +14721,6 @@ TEST_F(FormatTest, AlternativeOperators)
   */
 }
 
-TEST_F(FormatTest, NotCastRPaen) {
-
-  verifyFormat("void operator++(int) noexcept;");
-  verifyFormat("void operator++(int &) noexcept;");
-  verifyFormat("void operator delete(void *, 

r374172 - [clang-format] Update noexcept reference qualifiers detection

2019-10-09 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Wed Oct  9 07:46:08 2019
New Revision: 374172

URL: http://llvm.org/viewvc/llvm-project?rev=374172=rev
Log:
[clang-format] Update noexcept reference qualifiers detection

Summary:
r373165 fixed an issue where a templated noexcept member function with a
reference qualifier would be indented more than expected:
```
// Formatting produced with LLVM style with AlwaysBreakTemplateDeclarations: Yes

// before r373165:
struct f {
  template 
  void bar() && noexcept {}
};

// after:
struct f {
  template 
  void bar() && noexcept {}
};

```
The way this is done is that in the AnnotatingParser in
`lib/FormatTokenAnnotator.cpp` the determination of the usage of a `&` or `&&`
(the line in determineTokenType

```
Current.Type = determineStarAmpUsage(...
```
is not performed in some cases anymore, combining with a few additional related
checks afterwards. The net effect of these checks results in the `&` or `&&`
token to start being classified as `TT_Unknown` in cases where before `r373165`
it would be classified as `TT_UnaryOperator` or `TT_PointerOrReference` by
`determineStarAmpUsage`.

This inadvertently caused 2 classes of regressions I'm aware of:

- The address-of `&` after a function assignment would be classified as
  `TT_Unknown`, causing spaces to surround it, disregarding style options:
```
// before r373165:
void (*fun_ptr)(void) = 

// after:
void (*fun_ptr)(void) = & fun;
```

- In cases where there is a function declaration list -- looking macro between
  a template line and the start of the function declaration, an `&` as part of
  the return type would be classified as `TT_Unknown`, causing spaces to
  surround it:
```
// before r373165:
template 
DEPRECATED("lala")
Type& foo();

// after:
template 
DEPRECATED("lala")
Type & foo();
```

In these cases the problems are rooted in the skipping of the classification of
a `&` (and similarly `&&`) by determineStarAmpUsage which effects the formatting
decisions later in the pipeline.

I've looked into the goal of r373165 and noticed that replacing `noexcept` with
`const` in the given example produces no extra indentation with the old code:
```
// before r373165:
struct f {
  template 
  int foo() & const {}
};

struct f {
  template 
  int foo() & noexcept {}
};
```

I investigated how clang-format annotated these two examples differently to
determine the places where the processing of both diverges in the pipeline.
There were two places where the processing diverges, causing the extra indent in
the `noexcept` case:
1. The `const` is annotated as a `TT_TrailingAnnotation`, whereas `noexcept`
   is annotated as `TT_Unknown`. I've updated the `determineTokenType` function
   to account for this by adding a missing `tok:kw_noexcept` to the clause that
   marks a token as `TT_TrailingAnnotation`.
2. The `&` in the second example is wrongly identified as `TT_BinaryOperator`
   in `determineStarAmpUsage`. This is the reason for the extra indentation --
   clang-format gets confused and thinks this is an expression.
   I've updated `determineStarAmpUsage` to check for `tok:kw_noexcept`.

With these two updates in place, the additional parsing introduced by r373165
becomes unnecessary and all added tests pass (with updates, as now clang-format
respects the style configuration for spaces around the `&` in the test
examples).
I've removed these additions and added regression tests for the cases above.

Reviewers: AndWass, MyDeveloperDay

Reviewed By: MyDeveloperDay

Subscribers: cfe-commits

Tags: #clang, #clang-format

Differential Revision: https://reviews.llvm.org/D68695

Modified:
cfe/trunk/lib/Format/TokenAnnotator.cpp
cfe/trunk/unittests/Format/FormatTest.cpp

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=374172=374171=374172=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Wed Oct  9 07:46:08 2019
@@ -15,6 +15,7 @@
 #include "TokenAnnotator.h"
 #include "FormatToken.h"
 #include "clang/Basic/SourceManager.h"
+#include "clang/Basic/TokenKinds.h"
 #include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/Support/Debug.h"
 
@@ -65,7 +66,7 @@ public:
   AnnotatingParser(const FormatStyle , AnnotatedLine ,
const AdditionalKeywords )
   : Style(Style), Line(Line), CurrentToken(Line.First), AutoFound(false),
-TrailingReturnFound(false), Keywords(Keywords) {
+Keywords(Keywords) {
 Contexts.push_back(Context(tok::unknown, 1, /*IsExpression=*/false));
 resetTokenMetadata(CurrentToken);
   }
@@ -1397,11 +1398,7 @@ private:
!Current.Previous->is(tok::kw_operator)) {
   // not auto operator->() -> xxx;
   Current.Type = TT_TrailingReturnArrow;
-  TrailingReturnFound = true;
-} else if (Current.is(tok::star) ||
-   

r368280 - [clang-format] fix crash involving invalid preprocessor line

2019-08-08 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Thu Aug  8 04:56:18 2019
New Revision: 368280

URL: http://llvm.org/viewvc/llvm-project?rev=368280=rev
Log:
[clang-format] fix crash involving invalid preprocessor line

Summary:
This (invalid) fragment is crashing clang-format:
```
#if 1
int x;
#elif
int y;
#endif
```

The reason being that the parser expects a token after `#elif`, and the
subsequent parsing of the next line does not check if `CurrentToken` is null.

Reviewers: gribozavr

Reviewed By: gribozavr

Subscribers: cfe-commits

Tags: #clang

Differential Revision: https://reviews.llvm.org/D65940

Modified:
cfe/trunk/lib/Format/TokenAnnotator.cpp
cfe/trunk/unittests/Format/FormatTest.cpp

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=368280=368279=368280=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Thu Aug  8 04:56:18 2019
@@ -1099,6 +1099,8 @@ private:
 
 public:
   LineType parseLine() {
+if (!CurrentToken)
+  return LT_Invalid;
 NonTemplateLess.clear();
 if (CurrentToken->is(tok::hash))
   return parsePreprocessorDirective();

Modified: cfe/trunk/unittests/Format/FormatTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTest.cpp?rev=368280=368279=368280=diff
==
--- cfe/trunk/unittests/Format/FormatTest.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTest.cpp Thu Aug  8 04:56:18 2019
@@ -3087,6 +3087,15 @@ TEST_F(FormatTest, IndentPreprocessorDir
"#endif\n"
"#endif\n",
Style);
+  // Don't crash if there is an #elif directive without a condition.
+  verifyFormat("#if 1\n"
+   "int x;\n"
+   "#elif\n"
+   "int y;\n"
+   "#else\n"
+   "int z;\n"
+   "#endif",
+   Style);
   // FIXME: This doesn't 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


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r367012 - Update some tests after r366702

2019-07-25 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Thu Jul 25 05:15:46 2019
New Revision: 367012

URL: http://llvm.org/viewvc/llvm-project?rev=367012=rev
Log:
Update some tests after r366702

Summary:
r366702 added a set of new clang-cl -- specific openmp flags together with 
tests.
The way the newly added tests work is problematic: consider for example this
asertion:
```
// RUN: %clang_cl --target=x86_64-windows-msvc /openmp -### -- %s 2>&1 | 
FileCheck --check-prefix=CHECK-CC1-OPENMP %s
...
// CHECK-CC1-OPENMP: "-fopenmp"
```

It asserts that an `/openmp` flag should expand into `-fopenmp`. This however
depends on the default value of Clang's CLANG_DEFAULT_OPENMP_RUNTIME value.
Indeed, the code that adds `-fopenmp` to the output only does it if the default
runtime is `libomp` or `libiomp5`, not when it is `libgomp`.

I've updated the tests to not depend on the default value of this setting by
specifying the runtime to use explicitly in each assertion.

Reviewers: jdoerfert

Subscribers: cfe-commits

Tags: #clang

Differential Revision: https://reviews.llvm.org/D65272

Modified:
cfe/trunk/test/Driver/fopenmp.c

Modified: cfe/trunk/test/Driver/fopenmp.c
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/test/Driver/fopenmp.c?rev=367012=367011=367012=diff
==
--- cfe/trunk/test/Driver/fopenmp.c (original)
+++ cfe/trunk/test/Driver/fopenmp.c Thu Jul 25 05:15:46 2019
@@ -13,9 +13,12 @@
 // RUN: %clang -target x86_64-windows-gnu -fopenmp=libomp -c %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-CC1-OPENMP
 // RUN: %clang -target x86_64-windows-gnu -fopenmp=libgomp -c %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-CC1-NO-OPENMP
 // RUN: %clang -target x86_64-windows-gnu -fopenmp=libiomp5 -c %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-CC1-OPENMP
-// RUN: %clang -target x86_64-windows-gnu -fopenmp=libiomp5 -c %s -### 2>&1 | 
FileCheck %s --check-prefix=CHECK-CC1-OPENMP
-// RUN: %clang_cl --target=x86_64-windows-msvc /openmp -### -- %s 2>&1 | 
FileCheck --check-prefix=CHECK-CC1-OPENMP %s
-// RUN: %clang_cl --target=i686-windows-msvc /openmp:experimental -### -- %s 
2>&1 | FileCheck --check-prefix=CHECK-CC1-OPENMP %s
+// RUN: %clang_cl --target=x86_64-windows-msvc /clang:-fopenmp=libomp /openmp 
-### -- %s 2>&1 | FileCheck %s --check-prefix=CHECK-CC1-OPENMP
+// RUN: %clang_cl --target=x86_64-windows-msvc /clang:-fopenmp=libgomp /openmp 
-### -- %s 2>&1 | FileCheck %s --check-prefix=CHECK-CC1-NO-OPENMP
+// RUN: %clang_cl --target=x86_64-windows-msvc /clang:-fopenmp=libiomp5 
/openmp -### -- %s 2>&1 | FileCheck %s --check-prefix=CHECK-CC1-OPENMP
+// RUN: %clang_cl --target=x86_64-windows-msvc /clang:-fopenmp=libomp 
/openmp:experimental -### -- %s 2>&1 | FileCheck %s 
--check-prefix=CHECK-CC1-OPENMP
+// RUN: %clang_cl --target=x86_64-windows-msvc /clang:-fopenmp=libgomp 
/openmp:experimental -### -- %s 2>&1 | FileCheck %s 
--check-prefix=CHECK-CC1-NO-OPENMP
+// RUN: %clang_cl --target=x86_64-windows-msvc /clang:-fopenmp=libiomp5 
/openmp:experimental -### -- %s 2>&1 | FileCheck %s 
--check-prefix=CHECK-CC1-OPENMP
 // RUN: %clang_cl --target=x86_64-windows-msvc /openmp- -### -- %s 2>&1 | 
FileCheck --check-prefix=CHECK-CC1-NO-OPENMP %s
 //
 // CHECK-CC1-OPENMP: "-cc1"


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r360411 - Revert "Revert "[clang-format] Keep protobuf "package" statement on one line""

2019-05-10 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Fri May 10 02:15:11 2019
New Revision: 360411

URL: http://llvm.org/viewvc/llvm-project?rev=360411=rev
Log:
Revert "Revert "[clang-format] Keep protobuf "package" statement on one line""

Summary:
Top-level "package" and "import" statements should generally be kept on
one line, for all languages.



This reverts commit rL356912.
The regression from rL356835 was fixed via rC358275.

Reviewers: krasimir, sammccall, MyDeveloperDay, xinz, dchai, klimek

Reviewed By: krasimir, xinz, dchai

Subscribers: cfe-commits

Tags: #clang

Differential Revision: https://reviews.llvm.org/D60661

Modified:
cfe/trunk/lib/Format/TokenAnnotator.cpp
cfe/trunk/unittests/Format/FormatTestProto.cpp

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=360411=360410=360411=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Fri May 10 02:15:11 2019
@@ -1119,10 +1119,10 @@ public:
   return LT_ImportStatement;
 }
 
-// In .proto files, top-level options are very similar to import statements
-// and should not be line-wrapped.
+// In .proto files, top-level options and package statements are very
+// similar to import statements and should not be line-wrapped.
 if (Style.Language == FormatStyle::LK_Proto && Line.Level == 0 &&
-CurrentToken->is(Keywords.kw_option)) {
+CurrentToken->isOneOf(Keywords.kw_option, Keywords.kw_package)) {
   next();
   if (CurrentToken && CurrentToken->is(tok::identifier)) {
 while (CurrentToken)

Modified: cfe/trunk/unittests/Format/FormatTestProto.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestProto.cpp?rev=360411=360410=360411=diff
==
--- cfe/trunk/unittests/Format/FormatTestProto.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestProto.cpp Fri May 10 02:15:11 2019
@@ -397,6 +397,16 @@ TEST_F(FormatTestProto, FormatsOptions)
"};");
 }
 
+TEST_F(FormatTestProto, DoesntWrapPackageStatements) {
+  verifyFormat(
+  "package"
+  " some.really.long.package.that.exceeds.the.column.limit;");
+}
+
+TEST_F(FormatTestProto, TrailingCommentAfterPackage) {
+  verifyFormat("package foo.pkg;  // comment\n");
+}
+
 TEST_F(FormatTestProto, FormatsService) {
   verifyFormat("service SearchService {\n"
"  rpc Search(SearchRequest) returns (SearchResponse) {\n"


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r358689 - [clang-format] Fix indent of trailing raw string param after newline

2019-04-18 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Thu Apr 18 10:14:05 2019
New Revision: 358689

URL: http://llvm.org/viewvc/llvm-project?rev=358689=rev
Log:
[clang-format] Fix indent of trailing raw string param after newline

Summary:
Currently clang-format uses ContinuationIndent to indent the contents of a raw
string literal that is the last parameter of the function call. This is to
achieve formatting similar to trailing:
```
f(1, 2, R"pb(
x: y)pb");
```
However this had the unfortunate consequence of producing format like this:
```
fff(1, 2,
R"pb(
a: b
)pb");
```

This patch makes clang-format consider indenting a trailing raw string param
after a newline based off the start of the format delimiter, producing:
```
fff(1, 2,
R"pb(
  a: b
)pb");
```

Reviewers: djasper

Reviewed By: djasper

Subscribers: cfe-commits

Tags: #clang

Differential Revision: https://reviews.llvm.org/D60558

Modified:
cfe/trunk/lib/Format/ContinuationIndenter.cpp
cfe/trunk/lib/Format/ContinuationIndenter.h
cfe/trunk/unittests/Format/FormatTestRawStrings.cpp

Modified: cfe/trunk/lib/Format/ContinuationIndenter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/ContinuationIndenter.cpp?rev=358689=358688=358689=diff
==
--- cfe/trunk/lib/Format/ContinuationIndenter.cpp (original)
+++ cfe/trunk/lib/Format/ContinuationIndenter.cpp Thu Apr 18 10:14:05 2019
@@ -1196,7 +1196,8 @@ unsigned ContinuationIndenter::moveState
   State.Column += Current.ColumnWidth;
   State.NextToken = State.NextToken->Next;
 
-  unsigned Penalty = handleEndOfLine(Current, State, DryRun, AllowBreak);
+  unsigned Penalty =
+  handleEndOfLine(Current, State, DryRun, AllowBreak, Newline);
 
   if (Current.Role)
 Current.Role->formatFromToken(State, this, DryRun);
@@ -1490,7 +1491,7 @@ static unsigned getLastLineEndColumn(Str
 
 unsigned ContinuationIndenter::reformatRawStringLiteral(
 const FormatToken , LineState ,
-const FormatStyle , bool DryRun) {
+const FormatStyle , bool DryRun, bool Newline) {
   unsigned StartColumn = State.Column - Current.ColumnWidth;
   StringRef OldDelimiter = *getRawStringDelimiter(Current.TokenText);
   StringRef NewDelimiter =
@@ -1530,8 +1531,10 @@ unsigned ContinuationIndenter::reformatR
   // source.
   bool ContentStartsOnNewline = Current.TokenText[OldPrefixSize] == '\n';
   // If this token is the last parameter (checked by looking if it's followed 
by
-  // `)`, the base the indent off the line's nested block indent. Otherwise,
-  // base the indent off the arguments indent, so we can achieve:
+  // `)` and is not on a newline, the base the indent off the line's nested
+  // block indent. Otherwise, base the indent off the arguments indent, so we
+  // can achieve:
+  //
   // fff(1, 2, 3, R"pb(
   // key1: 1  #
   // key2: 2)pb");
@@ -1540,11 +1543,18 @@ unsigned ContinuationIndenter::reformatR
   // R"pb(
   //   key1: 1  #
   //   key2: 2
+  // )pb");
+  //
+  // fff(1, 2, 3,
+  // R"pb(
+  //   key1: 1  #
+  //   key2: 2
   // )pb",
   // 5);
-  unsigned CurrentIndent = (Current.Next && Current.Next->is(tok::r_paren))
-   ? State.Stack.back().NestedBlockIndent
-   : State.Stack.back().Indent;
+  unsigned CurrentIndent =
+  (!Newline && Current.Next && Current.Next->is(tok::r_paren))
+  ? State.Stack.back().NestedBlockIndent
+  : State.Stack.back().Indent;
   unsigned NextStartColumn = ContentStartsOnNewline
  ? CurrentIndent + Style.IndentWidth
  : FirstStartColumn;
@@ -1646,13 +1656,14 @@ unsigned ContinuationIndenter::addMultil
 
 unsigned ContinuationIndenter::handleEndOfLine(const FormatToken ,
LineState , bool DryRun,
-   bool AllowBreak) {
+   bool AllowBreak, bool Newline) {
   unsigned Penalty = 0;
   // Compute the raw string style to use in case this is a raw string literal
   // that can be reformatted.
   auto RawStringStyle = getRawStringStyle(Current, State);
   if (RawStringStyle && !Current.Finalized) {
-Penalty = reformatRawStringLiteral(Current, State, *RawStringStyle, 
DryRun);
+Penalty = reformatRawStringLiteral(Current, State, *RawStringStyle, DryRun,
+   Newline);
   } else if (Current.IsMultiline && Current.isNot(TT_BlockComment)) {
 // Don't break multi-line tokens other than block comments and raw string
 // literals. Instead, just update the state.

Modified: cfe/trunk/lib/Format/ContinuationIndenter.h
URL: 

r358275 - [clang-format] Use SpacesBeforeTrailingComments for "option" directive

2019-04-12 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Fri Apr 12 03:11:34 2019
New Revision: 358275

URL: http://llvm.org/viewvc/llvm-project?rev=358275=rev
Log:
[clang-format] Use SpacesBeforeTrailingComments for "option" directive

Summary:
AnnotatingParser::next() is needed to implicitly set TT_BlockComment
versus TT_LineComment.  On most other paths through
AnnotatingParser::parseLine(), all tokens are consumed to achieve that.
This change updates one place where this wasn't done.

Contributed by @dchai!

Reviewers: krasimir

Reviewed By: krasimir

Subscribers: cfe-commits

Tags: #clang

Differential Revision: https://reviews.llvm.org/D60541

Modified:
cfe/trunk/lib/Format/TokenAnnotator.cpp
cfe/trunk/unittests/Format/FormatTestProto.cpp

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=358275=358274=358275=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Fri Apr 12 03:11:34 2019
@@ -1124,8 +1124,11 @@ public:
 if (Style.Language == FormatStyle::LK_Proto && Line.Level == 0 &&
 CurrentToken->is(Keywords.kw_option)) {
   next();
-  if (CurrentToken && CurrentToken->is(tok::identifier))
+  if (CurrentToken && CurrentToken->is(tok::identifier)) {
+while (CurrentToken)
+  next();
 return LT_ImportStatement;
+  }
 }
 
 bool KeywordVirtualFound = false;

Modified: cfe/trunk/unittests/Format/FormatTestProto.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestProto.cpp?rev=358275=358274=358275=diff
==
--- cfe/trunk/unittests/Format/FormatTestProto.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestProto.cpp Fri Apr 12 03:11:34 2019
@@ -193,6 +193,10 @@ TEST_F(FormatTestProto, DoesntWrapFileOp
  "\"some.really.long.package.that.exceeds.the.column.limit\";"));
 }
 
+TEST_F(FormatTestProto, TrailingCommentAfterFileOption) {
+  verifyFormat("option java_package = \"foo.pkg\";  // comment\n");
+}
+
 TEST_F(FormatTestProto, FormatsOptions) {
   verifyFormat("option (MyProto.options) = {\n"
"  field_a: OK\n"


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r357695 - [clang-format] Preserve include blocks in ObjC Google style

2019-04-04 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Thu Apr  4 07:04:26 2019
New Revision: 357695

URL: http://llvm.org/viewvc/llvm-project?rev=357695=rev
Log:
[clang-format] Preserve include blocks in ObjC Google style

Summary:
r357567 started to regroup include block for Google style; it was meant to apply
only for C++. This patch reverts this for ObjC.

Reviewers: ioeric

Reviewed By: ioeric

Subscribers: thakis, cfe-commits

Tags: #clang

Differential Revision: https://reviews.llvm.org/D60263

Modified:
cfe/trunk/lib/Format/Format.cpp
cfe/trunk/unittests/Format/SortIncludesTest.cpp

Modified: cfe/trunk/lib/Format/Format.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/Format.cpp?rev=357695=357694=357695=diff
==
--- cfe/trunk/lib/Format/Format.cpp (original)
+++ cfe/trunk/lib/Format/Format.cpp Thu Apr  4 07:04:26 2019
@@ -877,6 +877,11 @@ FormatStyle getGoogleStyle(FormatStyle::
   } else if (Language == FormatStyle::LK_ObjC) {
 GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
 GoogleStyle.ColumnLimit = 100;
+// "Regroup" doesn't work well for ObjC yet (main header heuristic,
+// relationship between ObjC standard library headers and other heades,
+// #imports, etc.)
+GoogleStyle.IncludeStyle.IncludeBlocks =
+tooling::IncludeStyle::IBS_Preserve;
   }
 
   return GoogleStyle;

Modified: cfe/trunk/unittests/Format/SortIncludesTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/SortIncludesTest.cpp?rev=357695=357694=357695=diff
==
--- cfe/trunk/unittests/Format/SortIncludesTest.cpp (original)
+++ cfe/trunk/unittests/Format/SortIncludesTest.cpp Thu Apr  4 07:04:26 2019
@@ -653,6 +653,18 @@ TEST_F(SortIncludesTest, DoNotOutputRepl
   EXPECT_EQ(Code, sort(Code, "input.h", 0));
 }
 
+
+TEST_F(SortIncludesTest, DoNotRegroupGroupsInGoogleObjCStyle) {
+  FmtStyle = getGoogleStyle(FormatStyle::LK_ObjC);
+
+  EXPECT_EQ("#include \n"
+"#include \n"
+"#include \"a.h\"",
+sort("#include \n"
+ "#include \n"
+ "#include \"a.h\""));
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r357599 - [clang-format] Do not emit replacements while regrouping if Cpp includes are OK

2019-04-03 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Wed Apr  3 08:16:04 2019
New Revision: 357599

URL: http://llvm.org/viewvc/llvm-project?rev=357599=rev
Log:
[clang-format] Do not emit replacements while regrouping if Cpp includes are OK

Summary:
Currently clang-format would always emit a replacement for multi-block #include
sections if `IBS_Regroup`, even if the sections are correct:
```
% cat ~/test.h
#include 

#include "b.h"
% bin/clang-format --output-replacements-xml -style=google ~/test.h


#include a.h>#include 
"b.h"

%
```

This change makes clang-format not emit replacements in this case.
The logic is similar to the one implemented for Java in r354452.

Reviewers: ioeric

Reviewed By: ioeric

Subscribers: cfe-commits

Tags: #clang

Differential Revision: https://reviews.llvm.org/D60199

Modified:
cfe/trunk/lib/Format/Format.cpp
cfe/trunk/unittests/Format/SortIncludesTest.cpp

Modified: cfe/trunk/lib/Format/Format.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/Format.cpp?rev=357599=357598=357599=diff
==
--- cfe/trunk/lib/Format/Format.cpp (original)
+++ cfe/trunk/lib/Format/Format.cpp Wed Apr  3 08:16:04 2019
@@ -1753,6 +1753,7 @@ FindCursorIndex(const SmallVectorImpl ,
 ArrayRef Ranges, StringRef 
FileName,
+StringRef Code,
 tooling::Replacements , unsigned *Cursor) 
{
   unsigned IncludesBeginOffset = Includes.front().Offset;
   unsigned IncludesEndOffset =
@@ -1788,6 +1789,10 @@ static void sortCppIncludes(const Format
 
   // If the #includes are out of order, we generate a single replacement fixing
   // the entire block. Otherwise, no replacement is generated.
+  // In case Style.IncldueStyle.IncludeBlocks != IBS_Preserve, this check is 
not
+  // enough as additional newlines might be added or removed across #include
+  // blocks. This we handle below by generating the updated #imclude blocks and
+  // comparing it to the original.
   if (Indices.size() == Includes.size() &&
   std::is_sorted(Indices.begin(), Indices.end()) &&
   Style.IncludeStyle.IncludeBlocks == tooling::IncludeStyle::IBS_Preserve)
@@ -1808,6 +1813,11 @@ static void sortCppIncludes(const Format
 CurrentCategory = Includes[Index].Category;
   }
 
+  // If the #includes are out of order, we generate a single replacement fixing
+  // the entire range of blocks. Otherwise, no replacement is generated.
+  if (result == Code.substr(IncludesBeginOffset, IncludesBlockSize))
+return;
+
   auto Err = Replaces.add(tooling::Replacement(
   FileName, Includes.front().Offset, IncludesBlockSize, result));
   // FIXME: better error handling. For now, just skip the replacement for the
@@ -1876,8 +1886,8 @@ tooling::Replacements sortCppIncludes(co
   MainIncludeFound = true;
 IncludesInBlock.push_back({IncludeName, Line, Prev, Category});
   } else if (!IncludesInBlock.empty() && !EmptyLineSkipped) {
-sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces,
-Cursor);
+sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Code,
+Replaces, Cursor);
 IncludesInBlock.clear();
 FirstIncludeBlock = false;
   }
@@ -1887,8 +1897,10 @@ tooling::Replacements sortCppIncludes(co
   break;
 SearchFrom = Pos + 1;
   }
-  if (!IncludesInBlock.empty())
-sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Replaces, 
Cursor);
+  if (!IncludesInBlock.empty()) {
+sortCppIncludes(Style, IncludesInBlock, Ranges, FileName, Code, Replaces,
+Cursor);
+  }
   return Replaces;
 }
 

Modified: cfe/trunk/unittests/Format/SortIncludesTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/SortIncludesTest.cpp?rev=357599=357598=357599=diff
==
--- cfe/trunk/unittests/Format/SortIncludesTest.cpp (original)
+++ cfe/trunk/unittests/Format/SortIncludesTest.cpp Wed Apr  3 08:16:04 2019
@@ -8,6 +8,7 @@
 
 #include "FormatTestUtils.h"
 #include "clang/Format/Format.h"
+#include "llvm/ADT/None.h"
 #include "llvm/Support/Debug.h"
 #include "gtest/gtest.h"
 
@@ -24,9 +25,11 @@ protected:
   }
 
   std::string sort(StringRef Code, std::vector Ranges,
-   StringRef FileName = "input.cc") {
+   StringRef FileName = "input.cc",
+   unsigned ExpectedNumRanges = 1) {
 auto Replaces = sortIncludes(FmtStyle, Code, Ranges, FileName);
 Ranges = tooling::calculateRangesAfterReplacements(Replaces, Ranges);
+EXPECT_EQ(ExpectedNumRanges, Replaces.size());
 auto Sorted = applyAllReplacements(Code, Replaces);
 EXPECT_TRUE(static_cast(Sorted));
 auto Result = applyAllReplacements(
@@ -35,8 +38,10 @@ protected:
 return *Result;
   }
 
-  std::string sort(StringRef Code, StringRef FileName 

r356928 - [clang-format] Refine structured binding detection

2019-03-25 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Mon Mar 25 10:29:16 2019
New Revision: 356928

URL: http://llvm.org/viewvc/llvm-project?rev=356928=rev
Log:
[clang-format] Refine structured binding detection

Summary:
Revision r356575 had the unfortunate consequence that now clang-format never
detects an ObjC call expression after `&&`.

This patch tries harder to distinguish between C++17 structured bindings and
ObjC call expressions and adds a few regression tests.

Reviewers: klimek

Reviewed By: klimek

Subscribers: cfe-commits

Tags: #clang

Differential Revision: https://reviews.llvm.org/D59774

Modified:
cfe/trunk/lib/Format/TokenAnnotator.cpp
cfe/trunk/unittests/Format/FormatTestObjC.cpp

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=356928=356927=356928=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Mon Mar 25 10:29:16 2019
@@ -13,6 +13,7 @@
 
//===--===//
 
 #include "TokenAnnotator.h"
+#include "FormatToken.h"
 #include "clang/Basic/SourceManager.h"
 #include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/Support/Debug.h"
@@ -440,10 +441,11 @@ private:
 Contexts.back().InCSharpAttributeSpecifier;
 
 bool InsideInlineASM = Line.startsWith(tok::kw_asm);
+bool IsCppStructuredBinding = Left->isCppStructuredBinding(Style);
 bool StartsObjCMethodExpr =
-!InsideInlineASM && !CppArrayTemplates && Style.isCpp() &&
-!IsCpp11AttributeSpecifier && Contexts.back().CanBeExpression &&
-Left->isNot(TT_LambdaLSquare) &&
+!IsCppStructuredBinding && !InsideInlineASM && !CppArrayTemplates &&
+Style.isCpp() && !IsCpp11AttributeSpecifier &&
+Contexts.back().CanBeExpression && Left->isNot(TT_LambdaLSquare) &&
 !CurrentToken->isOneOf(tok::l_brace, tok::r_square) &&
 (!Parent ||
  Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
@@ -451,14 +453,12 @@ private:
  Parent->isUnaryOperator() ||
  // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
  Parent->isOneOf(TT_ObjCForIn, TT_CastRParen) ||
- // for (auto && [A,B] : C)  && structure binding seen as 
ObjCMethodExpr
- (Parent->isNot(tok::ampamp) &&
-  getBinOpPrecedence(Parent->Tok.getKind(), true, true) >
-  prec::Unknown));
+ (getBinOpPrecedence(Parent->Tok.getKind(), true, true) >
+  prec::Unknown));
 bool ColonFound = false;
 
 unsigned BindingIncrease = 1;
-if (Left->isCppStructuredBinding(Style)) {
+if (IsCppStructuredBinding) {
   Left->Type = TT_StructuredBindingLSquare;
 } else if (Left->is(TT_Unknown)) {
   if (StartsObjCMethodExpr) {

Modified: cfe/trunk/unittests/Format/FormatTestObjC.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestObjC.cpp?rev=356928=356927=356928=diff
==
--- cfe/trunk/unittests/Format/FormatTestObjC.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestObjC.cpp Mon Mar 25 10:29:16 2019
@@ -1357,6 +1357,30 @@ TEST_F(FormatTestObjC, DisambiguatesCall
   // verifyFormat("x = ([a foo:bar] >> b->c == 'd');");
 }
 
+TEST_F(FormatTestObjC,  DisambiguatesCallsFromStructuredBindings) {
+  verifyFormat("int f() {\n"
+   "  if (a && [f arg])\n"
+   "return 0;\n"
+   "}");
+  verifyFormat("int f() {\n"
+   "  if (a & [f arg])\n"
+   "return 0;\n"
+   "}");
+  verifyFormat("int f() {\n"
+   "  for (auto &[elem] : list)\n"
+   "return 0;\n"
+   "}");
+  verifyFormat("int f() {\n"
+   "  for (auto &&[elem] : list)\n"
+   "return 0;\n"
+   "}");
+  verifyFormat(
+  "int f() {\n"
+  "  for (auto /**/ const /**/ volatile /**/ && /**/ [elem] : list)\n"
+  "return 0;\n"
+  "}");
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r355831 - clang-format: distinguish ObjC call subexpressions after r355434

2019-03-11 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Mon Mar 11 09:02:52 2019
New Revision: 355831

URL: http://llvm.org/viewvc/llvm-project?rev=355831=rev
Log:
clang-format: distinguish ObjC call subexpressions after r355434

Summary:
The revision r355434 had the unfortunate side-effect that it started to
recognize certain ObjC expressions with a call subexpression followed by a
`a->b` subexpression as C++ lambda expressions.

This patch adds a bit of logic to handle these cases and documents them in
tests.

The commented-out test cases in the new test suite are ones that were
problematic before r355434.

Reviewers: MyDeveloperDay, gribozavr

Reviewed By: MyDeveloperDay, gribozavr

Subscribers: MyDeveloperDay, cfe-commits

Tags: #clang

Differential Revision: https://reviews.llvm.org/D59210

Modified:
cfe/trunk/lib/Format/UnwrappedLineParser.cpp
cfe/trunk/unittests/Format/FormatTestObjC.cpp

Modified: cfe/trunk/lib/Format/UnwrappedLineParser.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/UnwrappedLineParser.cpp?rev=355831=355830=355831=diff
==
--- cfe/trunk/lib/Format/UnwrappedLineParser.cpp (original)
+++ cfe/trunk/lib/Format/UnwrappedLineParser.cpp Mon Mar 11 09:02:52 2019
@@ -1401,6 +1401,8 @@ bool UnwrappedLineParser::tryToParseLamb
   if (!tryToParseLambdaIntroducer())
 return false;
 
+  bool SeenArrow = false;
+
   while (FormatTok->isNot(tok::l_brace)) {
 if (FormatTok->isSimpleTypeSpecifier()) {
   nextToken();
@@ -1423,8 +1425,19 @@ bool UnwrappedLineParser::tryToParseLamb
 case tok::coloncolon:
 case tok::kw_mutable:
 case tok::kw_noexcept:
+  nextToken();
+  break;
 // Specialization of a template with an integer parameter can contain
 // arithmetic, logical, comparison and ternary operators.
+//
+// FIXME: This also accepts sequences of operators that are not in the 
scope
+// of a template argument list.
+//
+// In a C++ lambda a template type can only occur after an arrow. We use
+// this as an heuristic to distinguish between Objective-C expressions
+// followed by an `a->b` expression, such as:
+// ([obj func:arg] + a->b)
+// Otherwise the code below would parse as a lambda.
 case tok::plus:
 case tok::minus:
 case tok::exclaim:
@@ -1444,13 +1457,17 @@ bool UnwrappedLineParser::tryToParseLamb
 case tok::colon:
 case tok::kw_true:
 case tok::kw_false:
-  nextToken();
-  break;
+  if (SeenArrow) {
+nextToken();
+break;
+  }
+  return true;
 case tok::arrow:
   // This might or might not actually be a lambda arrow (this could be an
   // ObjC method invocation followed by a dereferencing arrow). We might
   // reset this back to TT_Unknown in TokenAnnotator.
   FormatTok->Type = TT_LambdaArrow;
+  SeenArrow = true;
   nextToken();
   break;
 default:

Modified: cfe/trunk/unittests/Format/FormatTestObjC.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestObjC.cpp?rev=355831=355830=355831=diff
==
--- cfe/trunk/unittests/Format/FormatTestObjC.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestObjC.cpp Mon Mar 11 09:02:52 2019
@@ -1329,6 +1329,34 @@ TEST_F(FormatTestObjC, AlwaysBreakBefore
"   @\"f\"];");
 }
 
+TEST_F(FormatTestObjC, DisambiguatesCallsFromCppLambdas) {
+  verifyFormat("x = ([a foo:bar] && b->c == 'd');");
+  verifyFormat("x = ([a foo:bar] + b->c == 'd');");
+  verifyFormat("x = ([a foo:bar] + !b->c == 'd');");
+  verifyFormat("x = ([a foo:bar] + ~b->c == 'd');");
+  verifyFormat("x = ([a foo:bar] - b->c == 'd');");
+  verifyFormat("x = ([a foo:bar] / b->c == 'd');");
+  verifyFormat("x = ([a foo:bar] % b->c == 'd');");
+  verifyFormat("x = ([a foo:bar] | b->c == 'd');");
+  verifyFormat("x = ([a foo:bar] || b->c == 'd');");
+  verifyFormat("x = ([a foo:bar] && b->c == 'd');");
+  verifyFormat("x = ([a foo:bar] == b->c == 'd');");
+  verifyFormat("x = ([a foo:bar] != b->c == 'd');");
+  verifyFormat("x = ([a foo:bar] <= b->c == 'd');");
+  verifyFormat("x = ([a foo:bar] >= b->c == 'd');");
+  verifyFormat("x = ([a foo:bar] << b->c == 'd');");
+  verifyFormat("x = ([a foo:bar] ? b->c == 'd' : 'e');");
+  // FIXME: The following are wrongly classified as C++ lambda expressions.
+  // For example this code:
+  //   x = ([a foo:bar] & b->c == 'd');
+  // is formatted as:
+  //   x = ([a foo:bar] & b -> c == 'd');
+  // verifyFormat("x = ([a foo:bar] & b->c == 'd');");
+  // verifyFormat("x = ([a foo:bar] > b->c == 'd');");
+  // verifyFormat("x = ([a foo:bar] < b->c == 'd');");
+  // verifyFormat("x = ([a foo:bar] >> b->c == 'd');");
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang


___
cfe-commits mailing list

r354452 - [clang-format] Do not emit replacements if Java imports are OK

2019-02-20 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Wed Feb 20 03:44:21 2019
New Revision: 354452

URL: http://llvm.org/viewvc/llvm-project?rev=354452=rev
Log:
[clang-format] Do not emit replacements if Java imports are OK

Summary:
Currently clang-format would always emit a replacement for a block of Java 
imports even if it is correctly formatted:
```
% cat /tmp/Aggregator.java
import X;
% clang-format /tmp/Aggregator.java
import X;
% clang-format -output-replacements-xml /tmp/Aggregator.java


import X;

%
```
This change makes clang-format not emit replacements in this case. Note that
there is logic to not emit replacements in this case for C++.

Reviewers: ioeric

Reviewed By: ioeric

Subscribers: jdoerfert, cfe-commits

Tags: #clang

Differential Revision: https://reviews.llvm.org/D58436

Modified:
cfe/trunk/lib/Format/Format.cpp
cfe/trunk/unittests/Format/SortImportsTestJava.cpp

Modified: cfe/trunk/lib/Format/Format.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/Format.cpp?rev=354452=354451=354452=diff
==
--- cfe/trunk/lib/Format/Format.cpp (original)
+++ cfe/trunk/lib/Format/Format.cpp Wed Feb 20 03:44:21 2019
@@ -1853,6 +1853,7 @@ static unsigned findJavaImportGroup(cons
 static void sortJavaImports(const FormatStyle ,
 const SmallVectorImpl 
,
 ArrayRef Ranges, StringRef 
FileName,
+StringRef Code,
 tooling::Replacements ) {
   unsigned ImportsBeginOffset = Imports.front().Offset;
   unsigned ImportsEndOffset =
@@ -1868,12 +1869,12 @@ static void sortJavaImports(const Format
 findJavaImportGroup(Style, Imports[i].Identifier));
   }
   llvm::sort(Indices, [&](unsigned LHSI, unsigned RHSI) {
-// Negating IsStatic to push static imports above non-static imports.
-return std::make_tuple(!Imports[LHSI].IsStatic, JavaImportGroups[LHSI],
-   Imports[LHSI].Identifier) <
-   std::make_tuple(!Imports[RHSI].IsStatic, JavaImportGroups[RHSI],
-   Imports[RHSI].Identifier);
-  });
+// Negating IsStatic to push static imports above non-static imports.
+return std::make_tuple(!Imports[LHSI].IsStatic, JavaImportGroups[LHSI],
+   Imports[LHSI].Identifier) <
+   std::make_tuple(!Imports[RHSI].IsStatic, JavaImportGroups[RHSI],
+   Imports[RHSI].Identifier);
+  });
 
   // Deduplicate imports.
   Indices.erase(std::unique(Indices.begin(), Indices.end(),
@@ -1902,6 +1903,11 @@ static void sortJavaImports(const Format
 CurrentImportGroup = JavaImportGroups[Index];
   }
 
+  // If the imports are out of order, we generate a single replacement fixing
+  // the entire block. Otherwise, no replacement is generated.
+  if (result == Code.substr(Imports.front().Offset, ImportsBlockSize))
+return;
+
   auto Err = Replaces.add(tooling::Replacement(FileName, 
Imports.front().Offset,
ImportsBlockSize, result));
   // FIXME: better error handling. For now, just skip the replacement for the
@@ -1967,7 +1973,7 @@ tooling::Replacements sortJavaImports(co
 SearchFrom = Pos + 1;
   }
   if (!ImportsInBlock.empty())
-sortJavaImports(Style, ImportsInBlock, Ranges, FileName, Replaces);
+sortJavaImports(Style, ImportsInBlock, Ranges, FileName, Code, Replaces);
   return Replaces;
 }
 

Modified: cfe/trunk/unittests/Format/SortImportsTestJava.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/SortImportsTestJava.cpp?rev=354452=354451=354452=diff
==
--- cfe/trunk/unittests/Format/SortImportsTestJava.cpp (original)
+++ cfe/trunk/unittests/Format/SortImportsTestJava.cpp Wed Feb 20 03:44:21 2019
@@ -262,6 +262,14 @@ TEST_F(SortImportsTestJava, NoNewlineAtE
  "import org.a;"));
 }
 
+TEST_F(SortImportsTestJava, NoReplacementsForValidImports) {
+  // Identical #includes have led to a failure with an unstable sort.
+  std::string Code = "import org.a;\n"
+ "import org.b;\n";
+  EXPECT_TRUE(
+  sortIncludes(FmtStyle, Code, GetCodeRange(Code), "input.java").empty());
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r353033 - [clang-format] Fix breaking of qualified operator

2019-02-04 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Mon Feb  4 01:56:16 2019
New Revision: 353033

URL: http://llvm.org/viewvc/llvm-project?rev=353033=rev
Log:
[clang-format] Fix breaking of qualified operator

Summary:
From https://bugs.llvm.org/show_bug.cgi?id=40516
```
$ cat a.cpp
const NamespaceName::VeryLongClassName 
::VeryLongClassName::myFunction() {
  // do stuff
}

const NamespaceName::VeryLongClassName 
::VeryLongClassName::operator++() {
  // do stuff
}
$ ~/ll/build/opt/bin/clang-format -style=LLVM a.cpp
const NamespaceName::VeryLongClassName &
NamespaceName::VeryLongClassName::myFunction() {
  // do stuff
}

const NamespaceName::VeryLongClassName ::VeryLongClassName::
operator++() {
  // do stuff
}
```
What was happening is that the split penalty before `operator` was being set to
a smaller value by a prior if block. Moved checks around to fix this and added a
regression test.

Reviewers: djasper

Reviewed By: djasper

Tags: #clang

Differential Revision: https://reviews.llvm.org/D57604

Modified:
cfe/trunk/lib/Format/TokenAnnotator.cpp
cfe/trunk/unittests/Format/FormatTest.cpp

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=353033=353032=353033=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Mon Feb  4 01:56:16 2019
@@ -2249,6 +2249,9 @@ unsigned TokenAnnotator::splitPenalty(co
   return 500;
   }
 
+  if (Left.is(tok::coloncolon) ||
+  (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto))
+return 500;
   if (Right.isOneOf(TT_StartOfName, TT_FunctionDeclarationName) ||
   Right.is(tok::kw_operator)) {
 if (Line.startsWith(tok::kw_for) && Right.PartOfMultiVariableDeclStmt)
@@ -2267,9 +2270,6 @@ unsigned TokenAnnotator::splitPenalty(co
 return 160;
   if (Left.is(TT_CastRParen))
 return 100;
-  if (Left.is(tok::coloncolon) ||
-  (Right.is(tok::period) && Style.Language == FormatStyle::LK_Proto))
-return 500;
   if (Left.isOneOf(tok::kw_class, tok::kw_struct))
 return 5000;
   if (Left.is(tok::comment))

Modified: cfe/trunk/unittests/Format/FormatTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTest.cpp?rev=353033=353032=353033=diff
==
--- cfe/trunk/unittests/Format/FormatTest.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTest.cpp Mon Feb  4 01:56:16 2019
@@ -4183,6 +4183,18 @@ TEST_F(FormatTest, BreaksFunctionDeclara
Style);
 }
 
+TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) {
+  // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516:
+  // Prefer keeping `::` followed by `operator` together.
+  EXPECT_EQ("const ::bbb &\n"
+"c::operator++() {\n"
+"  stuff();\n"
+"}",
+format("const ::bbb\n"
+   "::operator++() { stuff(); }",
+   getLLVMStyleWithColumns(40)));
+}
+
 TEST_F(FormatTest, TrailingReturnType) {
   verifyFormat("auto foo() -> int;\n");
   verifyFormat("struct S {\n"


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r347465 - [clang-format] Do not treat asm clobber [ as ObjCExpr, refined

2018-11-22 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Thu Nov 22 06:49:55 2018
New Revision: 347465

URL: http://llvm.org/viewvc/llvm-project?rev=347465=rev
Log:
[clang-format] Do not treat asm clobber [ as ObjCExpr, refined

Summary:
r346756 refined clang-format to not treat the `[` in `asm (...: [] ..)` as an
ObjCExpr. However that's not enough, as we might have a comma-separated list of
such clobbers as in the newly added test.
This updates the detection to instead look at the Line's first token being `asm`
and not mark `[`-s as ObjCExprs in this case.

Reviewers: djasper, benhamilton

Reviewed By: djasper, benhamilton

Subscribers: benhamilton, cfe-commits

Differential Revision: https://reviews.llvm.org/D54795

Modified:
cfe/trunk/lib/Format/TokenAnnotator.cpp
cfe/trunk/unittests/Format/FormatTest.cpp

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=347465=347464=347465=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Thu Nov 22 06:49:55 2018
@@ -399,14 +399,15 @@ private:
 bool IsCpp11AttributeSpecifier = isCpp11AttributeSpecifier(*Left) ||
  Contexts.back().InCpp11AttributeSpecifier;
 
+bool InsideInlineASM = Line.startsWith(tok::kw_asm);
 bool StartsObjCMethodExpr =
-!CppArrayTemplates && Style.isCpp() && !IsCpp11AttributeSpecifier &&
-Contexts.back().CanBeExpression && Left->isNot(TT_LambdaLSquare) &&
+!InsideInlineASM && !CppArrayTemplates && Style.isCpp() &&
+!IsCpp11AttributeSpecifier && Contexts.back().CanBeExpression &&
+Left->isNot(TT_LambdaLSquare) &&
 !CurrentToken->isOneOf(tok::l_brace, tok::r_square) &&
 (!Parent ||
- (Parent->is(tok::colon) && Parent->isNot(TT_InlineASMColon)) ||
- Parent->isOneOf(tok::l_square, tok::l_paren, tok::kw_return,
- tok::kw_throw) ||
+ Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
+ tok::kw_return, tok::kw_throw) ||
  Parent->isUnaryOperator() ||
  // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
  Parent->isOneOf(TT_ObjCForIn, TT_CastRParen) ||

Modified: cfe/trunk/unittests/Format/FormatTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTest.cpp?rev=347465=347464=347465=diff
==
--- cfe/trunk/unittests/Format/FormatTest.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTest.cpp Thu Nov 22 06:49:55 2018
@@ -12762,6 +12762,30 @@ TEST_F(FormatTest, GuessedLanguageWithIn
" : [d] \"=rm\" (d)\n"
"   [e] \"rm\" (*e));\n"
"}"));
+  EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h",
+   "void f() {\n"
+   "  _asm (\"mov %[e], %[d]\"\n"
+   " : [d] \"=rm\" (d)\n"
+   "   [e] \"rm\" (*e));\n"
+   "}"));
+  EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h",
+   "void f() {\n"
+   "  __asm (\"mov %[e], %[d]\"\n"
+   " : [d] \"=rm\" (d)\n"
+   "   [e] \"rm\" (*e));\n"
+   "}"));
+  EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h",
+   "void f() {\n"
+   "  __asm__ (\"mov %[e], 
%[d]\"\n"
+   " : [d] \"=rm\" (d)\n"
+   "   [e] \"rm\" (*e));\n"
+   "}"));
+  EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h",
+   "void f() {\n"
+   "  asm (\"mov %[e], %[d]\"\n"
+   " : [d] \"=rm\" (d),\n"
+   "   [e] \"rm\" (*e));\n"
+   "}"));
   EXPECT_EQ(FormatStyle::LK_Cpp,
 guessLanguage("foo.h", "void f() {\n"
"  asm volatile (\"mov %[e], %[d]\"\n"


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r347307 - [clang-format] JS: don't treat is: as a type matcher

2018-11-20 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Tue Nov 20 06:22:43 2018
New Revision: 347307

URL: http://llvm.org/viewvc/llvm-project?rev=347307=rev
Log:
[clang-format] JS: don't treat is: as a type matcher

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

Modified:
cfe/trunk/lib/Format/TokenAnnotator.cpp
cfe/trunk/unittests/Format/FormatTestJS.cpp

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=347307=347306=347307=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Tue Nov 20 06:22:43 2018
@@ -3113,8 +3113,21 @@ bool TokenAnnotator::canBreakBefore(cons
 // Don't wrap between ":" and "!" of a strict prop init ("field!: type;").
 if (Left.is(tok::exclaim) && Right.is(tok::colon))
   return false;
-if (Right.is(Keywords.kw_is))
-  return false;
+// Look for is type annotations like:
+// function f(): a is B { ... }
+// Do not break before is in these cases.
+if (Right.is(Keywords.kw_is)) {
+  const FormatToken* Next = Right.getNextNonComment();
+  // If `is` is followed by a colon, it's likely that it's a dict key, so
+  // ignore it for this check.
+  // For example this is common in Polymer:
+  // Polymer({
+  //   is: 'name',
+  //   ...
+  // });
+  if (!Next || !Next->is(tok::colon))
+return false;
+}
 if (Left.is(Keywords.kw_in))
   return Style.BreakBeforeBinaryOperators == FormatStyle::BOS_None;
 if (Right.is(Keywords.kw_in))

Modified: cfe/trunk/unittests/Format/FormatTestJS.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestJS.cpp?rev=347307=347306=347307=diff
==
--- cfe/trunk/unittests/Format/FormatTestJS.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestJS.cpp Tue Nov 20 06:22:43 2018
@@ -1186,6 +1186,16 @@ TEST_F(FormatTestJS, WrapRespectsAutomat
getGoogleJSStyleWithColumns(25));
 }
 
+TEST_F(FormatTestJS, AddsIsTheDictKeyOnNewline) {
+  // Do not confuse is, the dict key with is, the type matcher. Put is, the 
dict
+  // key, on a newline.
+  verifyFormat("Polymer({\n"
+   "  is: '',  //\n"
+   "  rest: 1\n"
+   "});",
+   getGoogleJSStyleWithColumns(20));
+}
+
 TEST_F(FormatTestJS, AutomaticSemicolonInsertionHeuristic) {
   verifyFormat("a\n"
"b;",


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r346756 - [clang-format] Do not treat the asm clobber [ as ObjCExpr

2018-11-13 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Tue Nov 13 07:38:12 2018
New Revision: 346756

URL: http://llvm.org/viewvc/llvm-project?rev=346756=rev
Log:
[clang-format] Do not treat the asm clobber [ as ObjCExpr

Summary:
The opening square of an inline asm clobber was being annotated as an ObjCExpr.
This caused, amongst other things, the ObjCGuesser to guess header files
containing that pattern as ObjC files.

Reviewers: benhamilton

Reviewed By: benhamilton

Subscribers: cfe-commits

Differential Revision: https://reviews.llvm.org/D54111

Modified:
cfe/trunk/lib/Format/TokenAnnotator.cpp
cfe/trunk/unittests/Format/FormatTest.cpp

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=346756=346755=346756=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Tue Nov 13 07:38:12 2018
@@ -404,8 +404,9 @@ private:
 Contexts.back().CanBeExpression && Left->isNot(TT_LambdaLSquare) &&
 !CurrentToken->isOneOf(tok::l_brace, tok::r_square) &&
 (!Parent ||
- Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
- tok::kw_return, tok::kw_throw) ||
+ (Parent->is(tok::colon) && Parent->isNot(TT_InlineASMColon)) ||
+ Parent->isOneOf(tok::l_square, tok::l_paren, tok::kw_return,
+ tok::kw_throw) ||
  Parent->isUnaryOperator() ||
  // FIXME(bug 36976): ObjC return types shouldn't use TT_CastRParen.
  Parent->isOneOf(TT_ObjCForIn, TT_CastRParen) ||

Modified: cfe/trunk/unittests/Format/FormatTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTest.cpp?rev=346756=346755=346756=diff
==
--- cfe/trunk/unittests/Format/FormatTest.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTest.cpp Tue Nov 13 07:38:12 2018
@@ -12755,6 +12755,21 @@ TEST_F(FormatTest, GuessLanguageWithCare
   guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);"));
 }
 
+TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) {
+  EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h",
+   "void f() {\n"
+   "  asm (\"mov %[e], %[d]\"\n"
+   " : [d] \"=rm\" (d)\n"
+   "   [e] \"rm\" (*e));\n"
+   "}"));
+  EXPECT_EQ(FormatStyle::LK_Cpp,
+guessLanguage("foo.h", "void f() {\n"
+   "  asm volatile (\"mov %[e], %[d]\"\n"
+   " : [d] \"=rm\" (d)\n"
+   "   [e] \"rm\" (*e));\n"
+   "}"));
+}
+
 TEST_F(FormatTest, GuessLanguageWithChildLines) {
   EXPECT_EQ(FormatStyle::LK_Cpp,
 guessLanguage("foo.h", "#define FOO ({ std::string s; })"));


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r345753 - [clang-format] tweaked another case of lambda formatting

2018-10-31 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Wed Oct 31 10:56:57 2018
New Revision: 345753

URL: http://llvm.org/viewvc/llvm-project?rev=345753=rev
Log:
[clang-format] tweaked another case of lambda formatting

Summary:
This is done in order to improve cases where the lambda's body is moved too far 
to the right. Consider the following snippet with column limit set to 79:

```
void f() {
  leader::MakeThisCallHere(_service_,
   cq_.get(),
   [this, liveness](const leader::ReadRecordReq& req,
std::function done) {
 logger_->HandleReadRecord(
 req, resp, std::move(done));
   });

  leader::MakeAnother(_service_,
  cq_.get(),
  [this, liveness](const leader::ReadRecordReq& req,
   std::function done) {
logger_->HandleReadRecord(
req, resp, std::move(done), a);
  });
}
```

The tool favors extra indentation for the lambda body and so the code incurs 
extra wrapping and adjacent calls are indented to a different level. I find 
this behavior annoying and I'd like the tool to favor new lines and, thus, use 
the extra width.

The fix, reduced, brings the following formatting.

Before:

function(1,
 [] {
   DoStuff();
   //
 },
 1);

After:

function(
1,
[] {
  DoStuff();
  //
},
1);

Refer to the new tests in FormatTest.cpp

Contributed by oleg.smolsky!

Reviewers: djasper, klimek, krasimir

Subscribers: cfe-commits, owenpan

Tags: #clang

Differential Revision: https://reviews.llvm.org/D52676

Modified:
cfe/trunk/lib/Format/ContinuationIndenter.cpp
cfe/trunk/lib/Format/FormatToken.h
cfe/trunk/lib/Format/TokenAnnotator.cpp
cfe/trunk/lib/Format/UnwrappedLineFormatter.cpp
cfe/trunk/unittests/Format/FormatTest.cpp

Modified: cfe/trunk/lib/Format/ContinuationIndenter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/ContinuationIndenter.cpp?rev=345753=345752=345753=diff
==
--- cfe/trunk/lib/Format/ContinuationIndenter.cpp (original)
+++ cfe/trunk/lib/Format/ContinuationIndenter.cpp Wed Oct 31 10:56:57 2018
@@ -1135,7 +1135,8 @@ unsigned ContinuationIndenter::moveState
   //   }, a, b, c);
   if (Current.isNot(tok::comment) && Previous &&
   Previous->isOneOf(tok::l_brace, TT_ArrayInitializerLSquare) &&
-  !Previous->is(TT_DictLiteral) && State.Stack.size() > 1) {
+  !Previous->is(TT_DictLiteral) && State.Stack.size() > 1 &&
+  !State.Stack.back().HasMultipleNestedBlocks) {
 if (State.Stack[State.Stack.size() - 2].NestedBlockInlined && Newline)
   for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i)
 State.Stack[i].NoLineBreak = true;

Modified: cfe/trunk/lib/Format/FormatToken.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/FormatToken.h?rev=345753=345752=345753=diff
==
--- cfe/trunk/lib/Format/FormatToken.h (original)
+++ cfe/trunk/lib/Format/FormatToken.h Wed Oct 31 10:56:57 2018
@@ -599,6 +599,8 @@ public:
   /// Notifies the \c Role that a comma was found.
   virtual void CommaFound(const FormatToken *Token) {}
 
+  virtual const FormatToken *lastComma() { return nullptr; }
+
 protected:
   const FormatStyle 
 };
@@ -621,6 +623,12 @@ public:
 Commas.push_back(Token);
   }
 
+  const FormatToken *lastComma() override {
+if (Commas.empty())
+  return nullptr;
+return Commas.back();
+  }
+
 private:
   /// A struct that holds information on how to format a given list with
   /// a specific number of columns.

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=345753=345752=345753=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Wed Oct 31 10:56:57 2018
@@ -3049,6 +3049,30 @@ bool TokenAnnotator::mustBreakBefore(con
   return true;
   }
 
+  // Deal with lambda arguments in C++ - we want consistent line breaks whether
+  // they happen to be at arg0, arg1 or argN. The selection is a bit nuanced
+  // as aggressive line breaks are placed when the lambda is not the last arg.
+  if ((Style.Language == FormatStyle::LK_Cpp ||
+   Style.Language == FormatStyle::LK_ObjC) &&
+  Left.is(tok::l_paren) && Left.BlockParameterCount > 0 &&
+  !Right.isOneOf(tok::l_paren, TT_LambdaLSquare)) {
+// Multiple lambdas in the same function call force line breaks.
+if (Left.BlockParameterCount > 1)
+  return true;
+
+// A 

r345242 - [clang-format] Break before next parameter after a formatted multiline raw string parameter

2018-10-25 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Thu Oct 25 00:39:30 2018
New Revision: 345242

URL: http://llvm.org/viewvc/llvm-project?rev=345242=rev
Log:
[clang-format] Break before next parameter after a formatted multiline raw 
string parameter

Summary:
Currently clang-format breaks before the next parameter after multiline 
parameters (also recursively for the parent expressions of multiline 
parameters). However, it fails to do so for formatted multiline raw string 
literals:
```
$ cat test.cc
// Examples

// Regular multiline tokens
int x = f(R"(multi
 line)", 2);
}

int y = g(h(R"(multi
  line)"), 2);

// Formatted multiline tokens
int z = f(R"pb(multi: 1  #
   line: 2)pb", 2);

int w = g(h(R"pb(multi: 1  #
 line: 2)pb"), 2);
$ clang-format -style=google test.cc
// Examples

// Regular multiline tokens
int x = f(R"(multi
 line)",
  2);
}

int y = g(h(R"(multi
  line)"),
  2);

// Formatted multiline tokens
int z = f(R"pb(multi: 1  #
   line: 2)pb", 2);

int w = g(h(R"pb(multi: 1  #
 line: 2)pb"), 2);
```

This patch addresses this inconsistency by forcing breaking after multiline 
formatted raw string literals. This requires a little tweak to the indentation 
chosen for the contents of a formatted raw string literal: in case when that's 
a parameter and not the last one, the indentation is based off of the uniform 
indentation of all of the parameters.

Reviewers: sammccall

Reviewed By: sammccall

Subscribers: cfe-commits

Differential Revision: https://reviews.llvm.org/D52448

Modified:
cfe/trunk/lib/Format/ContinuationIndenter.cpp
cfe/trunk/unittests/Format/FormatTestRawStrings.cpp

Modified: cfe/trunk/lib/Format/ContinuationIndenter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/ContinuationIndenter.cpp?rev=345242=345241=345242=diff
==
--- cfe/trunk/lib/Format/ContinuationIndenter.cpp (original)
+++ cfe/trunk/lib/Format/ContinuationIndenter.cpp Thu Oct 25 00:39:30 2018
@@ -1502,10 +1502,25 @@ unsigned ContinuationIndenter::reformatR
   // violate the rectangle rule and visually flows within the surrounding
   // source.
   bool ContentStartsOnNewline = Current.TokenText[OldPrefixSize] == '\n';
-  unsigned NextStartColumn =
-  ContentStartsOnNewline
-  ? State.Stack.back().NestedBlockIndent + Style.IndentWidth
-  : FirstStartColumn;
+  // If this token is the last parameter (checked by looking if it's followed 
by
+  // `)`, the base the indent off the line's nested block indent. Otherwise,
+  // base the indent off the arguments indent, so we can achieve:
+  // fff(1, 2, 3, R"pb(
+  // key1: 1  #
+  // key2: 2)pb");
+  //
+  // fff(1, 2, 3,
+  // R"pb(
+  //   key1: 1  #
+  //   key2: 2
+  // )pb",
+  // 5);
+  unsigned CurrentIndent = (Current.Next && Current.Next->is(tok::r_paren))
+   ? State.Stack.back().NestedBlockIndent
+   : State.Stack.back().Indent;
+  unsigned NextStartColumn = ContentStartsOnNewline
+ ? CurrentIndent + Style.IndentWidth
+ : FirstStartColumn;
 
   // The last start column is the column the raw string suffix starts if it is
   // put on a newline.
@@ -1517,7 +1532,7 @@ unsigned ContinuationIndenter::reformatR
   // indent.
   unsigned LastStartColumn = Current.NewlinesBefore
  ? FirstStartColumn - NewPrefixSize
- : State.Stack.back().NestedBlockIndent;
+ : CurrentIndent;
 
   std::pair Fixes = internal::reformat(
   RawStringStyle, RawText, {tooling::Range(0, RawText.size())},
@@ -1527,8 +1542,7 @@ unsigned ContinuationIndenter::reformatR
   auto NewCode = applyAllReplacements(RawText, Fixes.first);
   tooling::Replacements NoFixes;
   if (!NewCode) {
-State.Column += Current.ColumnWidth;
-return 0;
+return addMultilineToken(Current, State);
   }
   if (!DryRun) {
 if (NewDelimiter != OldDelimiter) {
@@ -1577,6 +1591,13 @@ unsigned ContinuationIndenter::reformatR
   unsigned PrefixExcessCharacters =
   StartColumn + NewPrefixSize > Style.ColumnLimit ?
   StartColumn + NewPrefixSize - Style.ColumnLimit : 0;
+  bool IsMultiline =
+  ContentStartsOnNewline || (NewCode->find('\n') != std::string::npos);
+  if (IsMultiline) {
+// Break before further function parameters on all levels.
+for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
+  State.Stack[i].BreakBeforeParameter = true;
+  }
   return Fixes.second + PrefixExcessCharacters * Style.PenaltyExcessCharacter;
 }
 

Modified: cfe/trunk/unittests/Format/FormatTestRawStrings.cpp
URL: 

[clang-tools-extra] r344773 - [clangd] Fix msan failure after r344735 by initializing bitfields

2018-10-19 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Thu Oct 18 23:05:32 2018
New Revision: 344773

URL: http://llvm.org/viewvc/llvm-project?rev=344773=rev
Log:
[clangd] Fix msan failure after r344735 by initializing bitfields

That revision changed integer members to bitfields; the integers were
default initialized before and the bitfields lost that default
initialization. This started causing msan use-of-uninitialized memory in
clangd tests.

Modified:
clang-tools-extra/trunk/clangd/index/Index.h

Modified: clang-tools-extra/trunk/clangd/index/Index.h
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/index/Index.h?rev=344773=344772=344773=diff
==
--- clang-tools-extra/trunk/clangd/index/Index.h (original)
+++ clang-tools-extra/trunk/clangd/index/Index.h Thu Oct 18 23:05:32 2018
@@ -37,6 +37,7 @@ struct SymbolLocation {
   // Position is encoded into 32 bits to save space.
   // If Line/Column overflow, the value will be their maximum value.
   struct Position {
+Position() : Line(0), Column(0) {}
 void setLine(uint32_t Line);
 uint32_t line() const { return Line; }
 void setColumn(uint32_t Column);


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r344637 - Revert "[clangd] Refactor JSON-over-stdin/stdout code into Transport abstraction."

2018-10-16 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Tue Oct 16 11:44:41 2018
New Revision: 344637

URL: http://llvm.org/viewvc/llvm-project?rev=344637=rev
Log:
Revert "[clangd] Refactor JSON-over-stdin/stdout code into Transport 
abstraction."

This reverts commit r344620.
Breaks upstream bots.

Removed:
clang-tools-extra/trunk/clangd/JSONTransport.cpp
clang-tools-extra/trunk/clangd/Transport.h
clang-tools-extra/trunk/unittests/clangd/JSONTransportTests.cpp
Modified:
clang-tools-extra/trunk/clangd/CMakeLists.txt
clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
clang-tools-extra/trunk/clangd/ClangdLSPServer.h
clang-tools-extra/trunk/clangd/JSONRPCDispatcher.cpp
clang-tools-extra/trunk/clangd/JSONRPCDispatcher.h
clang-tools-extra/trunk/clangd/Protocol.cpp
clang-tools-extra/trunk/clangd/Protocol.h
clang-tools-extra/trunk/clangd/ProtocolHandlers.cpp
clang-tools-extra/trunk/clangd/tool/ClangdMain.cpp
clang-tools-extra/trunk/test/clangd/compile-commands-path-in-initialize.test
clang-tools-extra/trunk/test/clangd/completion-snippets.test
clang-tools-extra/trunk/test/clangd/completion.test
clang-tools-extra/trunk/test/clangd/crash-non-added-files.test
clang-tools-extra/trunk/test/clangd/execute-command.test
clang-tools-extra/trunk/test/clangd/input-mirror.test
clang-tools-extra/trunk/test/clangd/signature-help.test
clang-tools-extra/trunk/test/clangd/textdocument-didchange-fail.test
clang-tools-extra/trunk/test/clangd/trace.test
clang-tools-extra/trunk/test/clangd/xrefs.test
clang-tools-extra/trunk/unittests/clangd/CMakeLists.txt

Modified: clang-tools-extra/trunk/clangd/CMakeLists.txt
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/CMakeLists.txt?rev=344637=344636=344637=diff
==
--- clang-tools-extra/trunk/clangd/CMakeLists.txt (original)
+++ clang-tools-extra/trunk/clangd/CMakeLists.txt Tue Oct 16 11:44:41 2018
@@ -26,7 +26,6 @@ add_clang_library(clangDaemon
   GlobalCompilationDatabase.cpp
   Headers.cpp
   JSONRPCDispatcher.cpp
-  JSONTransport.cpp
   Logger.cpp
   Protocol.cpp
   ProtocolHandlers.cpp

Modified: clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp?rev=344637=344636=344637=diff
==
--- clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp (original)
+++ clang-tools-extra/trunk/clangd/ClangdLSPServer.cpp Tue Oct 16 11:44:41 2018
@@ -162,10 +162,7 @@ void ClangdLSPServer::onShutdown(Shutdow
   reply(nullptr);
 }
 
-void ClangdLSPServer::onExit(ExitParams ) {
-  // No work to do.
-  // JSONRPCDispatcher shuts down the transport after this notification.
-}
+void ClangdLSPServer::onExit(ExitParams ) { IsDone = true; }
 
 void ClangdLSPServer::onDocumentDidOpen(DidOpenTextDocumentParams ) {
   PathRef File = Params.textDocument.uri.file();
@@ -500,41 +497,39 @@ void ClangdLSPServer::onReference(Refere
  });
 }
 
-ClangdLSPServer::ClangdLSPServer(class Transport ,
+ClangdLSPServer::ClangdLSPServer(JSONOutput ,
  const clangd::CodeCompleteOptions ,
  llvm::Optional CompileCommandsDir,
  bool ShouldUseInMemoryCDB,
  const ClangdServer::Options )
-: Transport(Transport),
-  CDB(ShouldUseInMemoryCDB ? CompilationDB::makeInMemory()
-   : CompilationDB::makeDirectoryBased(
- std::move(CompileCommandsDir))),
+: Out(Out), CDB(ShouldUseInMemoryCDB ? CompilationDB::makeInMemory()
+ : CompilationDB::makeDirectoryBased(
+   std::move(CompileCommandsDir))),
   CCOpts(CCOpts), SupportedSymbolKinds(defaultSymbolKinds()),
   SupportedCompletionItemKinds(defaultCompletionItemKinds()),
   Server(new ClangdServer(CDB.getCDB(), FSProvider, /*DiagConsumer=*/*this,
   Opts)) {}
 
-bool ClangdLSPServer::run() {
+bool ClangdLSPServer::run(std::FILE *In, JSONStreamStyle InputStyle) {
+  assert(!IsDone && "Run was called before");
   assert(Server);
 
   // Set up JSONRPCDispatcher.
   JSONRPCDispatcher Dispatcher([](const json::Value ) {
 replyError(ErrorCode::MethodNotFound, "method not found");
-return true;
   });
   registerCallbackHandlers(Dispatcher, /*Callbacks=*/*this);
 
   // Run the Language Server loop.
-  bool CleanExit = true;
-  if (auto Err = Dispatcher.runLanguageServerLoop(Transport)) {
-elog("Transport error: {0}", std::move(Err));
-CleanExit = false;
-  }
+  runLanguageServerLoop(In, Out, InputStyle, Dispatcher, IsDone);
 
+  // Make sure IsDone is set to true after this method exits to ensure 
assertion
+  // at the 

r343862 - [clang-format] Java import sorting in clang-format

2018-10-05 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Fri Oct  5 10:19:26 2018
New Revision: 343862

URL: http://llvm.org/viewvc/llvm-project?rev=343862=rev
Log:
[clang-format] Java import sorting in clang-format

Contributed by SamMaier!

Added:
cfe/trunk/unittests/Format/SortImportsTestJava.cpp
Modified:
cfe/trunk/include/clang/Format/Format.h
cfe/trunk/lib/Format/Format.cpp
cfe/trunk/unittests/Format/CMakeLists.txt

Modified: cfe/trunk/include/clang/Format/Format.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Format/Format.h?rev=343862=343861=343862=diff
==
--- cfe/trunk/include/clang/Format/Format.h (original)
+++ cfe/trunk/include/clang/Format/Format.h Fri Oct  5 10:19:26 2018
@@ -1130,6 +1130,35 @@ struct FormatStyle {
   /// \endcode
   bool IndentWrappedFunctionNames;
 
+  /// A vector of prefixes ordered by the desired groups for Java imports.
+  ///
+  /// Each group is seperated by a newline. Static imports will also follow the
+  /// same grouping convention above all non-static imports. One group's prefix
+  /// can be a subset of another - the longest prefix is always matched. Within
+  /// a group, the imports are ordered lexicographically.
+  ///
+  /// In the .clang-format configuration file, this can be configured like:
+  /// \code{.yaml}
+  ///   JavaImportGroups: ['com.example', 'com', 'org']
+  /// \endcode
+  /// Which will result in imports being formatted as so:
+  /// \code{.java}
+  ///import static com.example.function1;
+  ///
+  ///import static com.test.function2;
+  ///
+  ///import static org.example.function3;
+  ///
+  ///import com.example.ClassA;
+  ///import com.example.Test;
+  ///import com.example.a.ClassB;
+  ///
+  ///import com.test.ClassC;
+  ///
+  ///import org.example.ClassD;
+  /// \endcode
+  std::vector JavaImportGroups;
+
   /// Quotation styles for JavaScript strings. Does not affect template
   /// strings.
   enum JavaScriptQuoteStyle {
@@ -1734,6 +1763,7 @@ struct FormatStyle {
IndentPPDirectives == R.IndentPPDirectives &&
IndentWidth == R.IndentWidth && Language == R.Language &&
IndentWrappedFunctionNames == R.IndentWrappedFunctionNames &&
+   JavaImportGroups == R.JavaImportGroups &&
JavaScriptQuotes == R.JavaScriptQuotes &&
JavaScriptWrapImports == R.JavaScriptWrapImports &&
KeepEmptyLinesAtTheStartOfBlocks ==

Modified: cfe/trunk/lib/Format/Format.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/Format.cpp?rev=343862=343861=343862=diff
==
--- cfe/trunk/lib/Format/Format.cpp (original)
+++ cfe/trunk/lib/Format/Format.cpp Fri Oct  5 10:19:26 2018
@@ -414,6 +414,7 @@ template <> struct MappingTraitshttps://chromium.googlesource.com/chromium/src/+/master/styleguide/java/java.md#Import-Order
+ChromiumStyle.JavaImportGroups = {
+"android",
+"com",
+"dalvik",
+"junit",
+"org",
+"com.google.android.apps.chrome",
+"org.chromium",
+"java",
+"javax",
+};
+ChromiumStyle.SortIncludes = true;
   } else if (Language == FormatStyle::LK_JavaScript) {
 ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
 ChromiumStyle.AllowShortLoopsOnASingleLine = false;
@@ -1608,6 +1623,14 @@ struct IncludeDirective {
   int Category;
 };
 
+struct JavaImportDirective {
+  StringRef Identifier;
+  StringRef Text;
+  unsigned Offset;
+  std::vector AssociatedCommentLines;
+  bool IsStatic;
+};
+
 } // end anonymous namespace
 
 // Determines whether 'Ranges' intersects with ('Start', 'End').
@@ -1726,7 +1749,7 @@ static void sortCppIncludes(const Format
 
 namespace {
 
-const char IncludeRegexPattern[] =
+const char CppIncludeRegexPattern[] =
 R"(^[\t\ ]*#[\t\ ]*(import|include)[^"<]*(["<][^">]*[">]))";
 
 } // anonymous namespace
@@ -1738,7 +1761,7 @@ tooling::Replacements sortCppIncludes(co
   unsigned *Cursor) {
   unsigned Prev = 0;
   unsigned SearchFrom = 0;
-  llvm::Regex IncludeRegex(IncludeRegexPattern);
+  llvm::Regex IncludeRegex(CppIncludeRegexPattern);
   SmallVector Matches;
   SmallVector IncludesInBlock;
 
@@ -1797,6 +1820,149 @@ tooling::Replacements sortCppIncludes(co
   return Replaces;
 }
 
+// Returns group number to use as a first order sort on imports. Gives UINT_MAX
+// if the import does not match any given groups.
+static unsigned findJavaImportGroup(const FormatStyle ,
+StringRef ImportIdentifier) {
+  unsigned LongestMatchIndex = UINT_MAX;
+  unsigned LongestMatchLength = 0;
+  for (unsigned I = 0; I < Style.JavaImportGroups.size(); I++) {
+std::string GroupPrefix = Style.JavaImportGroups[I];
+if (ImportIdentifier.startswith(GroupPrefix) &&
+GroupPrefix.length() > 

r343517 - [clang-format] Update comment, NFCI

2018-10-01 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Mon Oct  1 11:41:21 2018
New Revision: 343517

URL: http://llvm.org/viewvc/llvm-project?rev=343517=rev
Log:
[clang-format] Update comment, NFCI

The initializer of `ParameterCount` was updated from 1 to 0 in r175165,
but the comment was never touched:
https://github.com/llvm-mirror/clang/commit/9fc56f2636137fcde8acb3886ed6c7b84dfd

Modified:
cfe/trunk/lib/Format/FormatToken.h

Modified: cfe/trunk/lib/Format/FormatToken.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/FormatToken.h?rev=343517=343516=343517=diff
==
--- cfe/trunk/lib/Format/FormatToken.h (original)
+++ cfe/trunk/lib/Format/FormatToken.h Mon Oct  1 11:41:21 2018
@@ -188,10 +188,6 @@ struct FormatToken {
   bool ClosesTemplateDeclaration = false;
 
   /// Number of parameters, if this is "(", "[" or "<".
-  ///
-  /// This is initialized to 1 as we don't need to distinguish functions with
-  /// 0 parameters from functions with 1 parameter. Thus, we can simply count
-  /// the number of commas.
   unsigned ParameterCount = 0;
 
   /// Number of parameters that are nested blocks,


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r343513 - [clang-format] Fix typo in comment, NFCI

2018-10-01 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Mon Oct  1 11:18:00 2018
New Revision: 343513

URL: http://llvm.org/viewvc/llvm-project?rev=343513=rev
Log:
[clang-format] Fix typo in comment, NFCI

Modified:
cfe/trunk/lib/Format/FormatToken.h

Modified: cfe/trunk/lib/Format/FormatToken.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/FormatToken.h?rev=343513=343512=343513=diff
==
--- cfe/trunk/lib/Format/FormatToken.h (original)
+++ cfe/trunk/lib/Format/FormatToken.h Mon Oct  1 11:18:00 2018
@@ -268,7 +268,7 @@ struct FormatToken {
   /// \c true if this token ends a binary expression.
   bool EndsBinaryExpression = false;
 
-  /// Is this is an operator (or "."/"->") in a sequence of operators
+  /// If this is an operator (or "."/"->") in a sequence of operators
   /// with the same precedence, contains the 0-based operator index.
   unsigned OperatorIndex = 0;
 


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r339573 - [clang-format] Fix comment, NFC

2018-08-13 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Mon Aug 13 07:32:29 2018
New Revision: 339573

URL: http://llvm.org/viewvc/llvm-project?rev=339573=rev
Log:
[clang-format] Fix comment, NFC

Modified:
cfe/trunk/unittests/Format/FormatTestTextProto.cpp

Modified: cfe/trunk/unittests/Format/FormatTestTextProto.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestTextProto.cpp?rev=339573=339572=339573=diff
==
--- cfe/trunk/unittests/Format/FormatTestTextProto.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestTextProto.cpp Mon Aug 13 07:32:29 2018
@@ -1,4 +1,4 @@
-//===- unittest/Format/FormatTestProto.cpp 
===//
+//===- unittest/Format/FormatTestTextProto.cpp 
===//
 //
 // The LLVM Compiler Infrastructure
 //


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r339123 - [clang-format] comment reflow: add last line's penalty when ending broken

2018-08-07 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Tue Aug  7 03:23:24 2018
New Revision: 339123

URL: http://llvm.org/viewvc/llvm-project?rev=339123=rev
Log:
[clang-format] comment reflow: add last line's penalty when ending broken

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

Modified:
cfe/trunk/lib/Format/ContinuationIndenter.cpp
cfe/trunk/unittests/Format/FormatTestJS.cpp

Modified: cfe/trunk/lib/Format/ContinuationIndenter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/ContinuationIndenter.cpp?rev=339123=339122=339123=diff
==
--- cfe/trunk/lib/Format/ContinuationIndenter.cpp (original)
+++ cfe/trunk/lib/Format/ContinuationIndenter.cpp Tue Aug  7 03:23:24 2018
@@ -1840,7 +1840,8 @@ ContinuationIndenter::breakProtrudingTok
 // No break opportunity - update the penalty and continue with the next
 // logical line.
 if (LineIndex < EndIndex - 1)
-  // The last line's penalty is handled in addNextStateToQueue().
+  // The last line's penalty is handled in addNextStateToQueue() or 
when
+  // calling replaceWhitespaceAfterLastLine below.
   Penalty += Style.PenaltyExcessCharacter *
  (ContentStartColumn + RemainingTokenColumns - 
ColumnLimit);
 LLVM_DEBUG(llvm::dbgs() << "No break opportunity.\n");
@@ -2095,6 +2096,12 @@ ContinuationIndenter::breakProtrudingTok
   Token->getSplitAfterLastLine(TailOffset);
   if (SplitAfterLastLine.first != StringRef::npos) {
 LLVM_DEBUG(llvm::dbgs() << "Replacing whitespace after last line.\n");
+
+// We add the last line's penalty here, since that line is going to be 
split
+// now.
+Penalty += Style.PenaltyExcessCharacter *
+   (ContentStartColumn + RemainingTokenColumns - ColumnLimit);
+
 if (!DryRun)
   Token->replaceWhitespaceAfterLastLine(TailOffset, SplitAfterLastLine,
 Whitespaces);

Modified: cfe/trunk/unittests/Format/FormatTestJS.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestJS.cpp?rev=339123=339122=339123=diff
==
--- cfe/trunk/unittests/Format/FormatTestJS.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestJS.cpp Tue Aug  7 03:23:24 2018
@@ -2284,5 +2284,25 @@ TEST_F(FormatTestJS, BackslashesInCommen
"formatMe( );\n");
 }
 
+TEST_F(FormatTestJS, AddsLastLinePenaltyIfEndingIsBroken) {
+  EXPECT_EQ(
+  "a = function() {\n"
+  "  b = function() {\n"
+  "this.aaa[aaa] = .aa ?\n"
+  ".aa : /** @type "
+  "{..a.aaa} */\n"
+  "(..a.a.a);\n"
+  "  };\n"
+  "};",
+  format("a = function() {\n"
+ "  b = function() {\n"
+ "this.aaa[aaa] = .aa ? "
+ ".aa : /** @type "
+ "{..a.aaa} */\n"
+ "(..a.a.a);\n"
+ "  };\n"
+ "};"));
+}
+
 } // end namespace tooling
 } // end namespace clang


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r338839 - clang-format-diff: Make it work with python3 too

2018-08-03 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Fri Aug  3 03:04:58 2018
New Revision: 338839

URL: http://llvm.org/viewvc/llvm-project?rev=338839=rev
Log:
clang-format-diff: Make it work with python3 too

Summary: It is not necessary, but would be nice if the script run on python3 as 
well (as opposed to only python2, which is going to be deprecated 
https://pythonclock.org/)

Contributed by MarcoFalke!

Reviewers: krasimir

Reviewed By: krasimir

Subscribers: lebedev.ri, sammccall, cfe-commits

Differential Revision: https://reviews.llvm.org/D48098

Modified:
cfe/trunk/tools/clang-format/clang-format-diff.py

Modified: cfe/trunk/tools/clang-format/clang-format-diff.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/tools/clang-format/clang-format-diff.py?rev=338839=338838=338839=diff
==
--- cfe/trunk/tools/clang-format/clang-format-diff.py (original)
+++ cfe/trunk/tools/clang-format/clang-format-diff.py Fri Aug  3 03:04:58 2018
@@ -25,10 +25,12 @@ Example usage for git/svn users:
 import argparse
 import difflib
 import re
-import string
 import subprocess
-import StringIO
 import sys
+try:
+  from StringIO import StringIO
+except ImportError:
+   from io import StringIO
 
 
 def main():
@@ -84,14 +86,14 @@ def main():
 line_count = int(match.group(3))
   if line_count == 0:
 continue
-  end_line = start_line + line_count - 1;
+  end_line = start_line + line_count - 1
   lines_by_file.setdefault(filename, []).extend(
   ['-lines', str(start_line) + ':' + str(end_line)])
 
   # Reformat files containing changes in place.
-  for filename, lines in lines_by_file.iteritems():
+  for filename, lines in lines_by_file.items():
 if args.i and args.verbose:
-  print 'Formatting', filename
+  print('Formatting {}'.format(filename))
 command = [args.binary, filename]
 if args.i:
   command.append('-i')
@@ -100,20 +102,23 @@ def main():
 command.extend(lines)
 if args.style:
   command.extend(['-style', args.style])
-p = subprocess.Popen(command, stdout=subprocess.PIPE,
- stderr=None, stdin=subprocess.PIPE)
+p = subprocess.Popen(command,
+ stdout=subprocess.PIPE,
+ stderr=None,
+ stdin=subprocess.PIPE,
+ universal_newlines=True)
 stdout, stderr = p.communicate()
 if p.returncode != 0:
-  sys.exit(p.returncode);
+  sys.exit(p.returncode)
 
 if not args.i:
   with open(filename) as f:
 code = f.readlines()
-  formatted_code = StringIO.StringIO(stdout).readlines()
+  formatted_code = StringIO(stdout).readlines()
   diff = difflib.unified_diff(code, formatted_code,
   filename, filename,
   '(before formatting)', '(after formatting)')
-  diff_string = string.join(diff, '')
+  diff_string = ''.join(diff)
   if len(diff_string) > 0:
 sys.stdout.write(diff_string)
 


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r338524 - [clang-format] Add some text proto functions to Google style

2018-08-01 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Wed Aug  1 05:35:23 2018
New Revision: 338524

URL: http://llvm.org/viewvc/llvm-project?rev=338524=rev
Log:
[clang-format] Add some text proto functions to Google style

Summary: Adds 2 functions taking a text proto argument.

Reviewers: djasper, klimek

Reviewed By: djasper

Subscribers: acoomans, cfe-commits

Differential Revision: https://reviews.llvm.org/D50132

Modified:
cfe/trunk/lib/Format/Format.cpp

Modified: cfe/trunk/lib/Format/Format.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/Format.cpp?rev=338524=338523=338524=diff
==
--- cfe/trunk/lib/Format/Format.cpp (original)
+++ cfe/trunk/lib/Format/Format.cpp Wed Aug  1 05:35:23 2018
@@ -777,9 +777,11 @@ FormatStyle getGoogleStyle(FormatStyle::
   {
   "EqualsProto",
   "EquivToProto",
+  "PARSE_PARTIAL_TEXT_PROTO",
   "PARSE_TEST_PROTO",
   "PARSE_TEXT_PROTO",
   "ParseTextOrDie",
+  "ParseTextProtoOrDie",
   },
   /*CanonicalDelimiter=*/"",
   /*BasedOnStyle=*/"google",


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r338519 - [clang-format] Add @private to the list of jsdoc annotations

2018-08-01 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Wed Aug  1 04:48:04 2018
New Revision: 338519

URL: http://llvm.org/viewvc/llvm-project?rev=338519=rev
Log:
[clang-format] Add @private to the list of jsdoc annotations

Reviewers: mprobst

Reviewed By: mprobst

Subscribers: acoomans, cfe-commits

Differential Revision: https://reviews.llvm.org/D50138

Modified:
cfe/trunk/lib/Format/BreakableToken.cpp

Modified: cfe/trunk/lib/Format/BreakableToken.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/BreakableToken.cpp?rev=338519=338518=338519=diff
==
--- cfe/trunk/lib/Format/BreakableToken.cpp (original)
+++ cfe/trunk/lib/Format/BreakableToken.cpp Wed Aug  1 04:48:04 2018
@@ -514,7 +514,7 @@ unsigned BreakableBlockComment::getConte
 const llvm::StringSet<>
 BreakableBlockComment::ContentIndentingJavadocAnnotations = {
 "@param", "@return", "@returns", "@throws",  "@type", "@template",
-"@see",   "@deprecated", "@define",  "@exports", "@mods",
+"@see",   "@deprecated", "@define",  "@exports", "@mods", "@private",
 };
 
 unsigned BreakableBlockComment::getContentIndent(unsigned LineIndex) const {


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r338245 - [clang-format] Silence -Wdocumentation warnings

2018-07-30 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Mon Jul 30 05:22:41 2018
New Revision: 338245

URL: http://llvm.org/viewvc/llvm-project?rev=338245=rev
Log:
[clang-format] Silence -Wdocumentation warnings

introduced in r338232

Modified:
cfe/trunk/lib/Format/BreakableToken.h

Modified: cfe/trunk/lib/Format/BreakableToken.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/BreakableToken.h?rev=338245=338244=338245=diff
==
--- cfe/trunk/lib/Format/BreakableToken.h (original)
+++ cfe/trunk/lib/Format/BreakableToken.h Mon Jul 30 05:22:41 2018
@@ -139,12 +139,14 @@ public:
   /// Returns additional content indent required for the second line after the
   /// content at line \p LineIndex is broken.
   ///
-  /// For example, Javadoc @param annotations require and indent of 4 spaces 
and
-  /// in this example getContentIndex(1) returns 4.
-  /// /**
-  ///  * @param loong line
-  ///  * continuation
-  ///  */
+  // (Next lines do not start with `///` since otherwise -Wdocumentation picks
+  // up the example annotations and generates warnings for them)
+  // For example, Javadoc @param annotations require and indent of 4 spaces and
+  // in this example getContentIndex(1) returns 4.
+  // /**
+  //  * @param loong line
+  //  * continuation
+  //  */
   virtual unsigned getContentIndent(unsigned LineIndex) const {
 return 0;
   }


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r338232 - [clang-format] Indent after breaking Javadoc annotated line

2018-07-30 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Mon Jul 30 01:45:45 2018
New Revision: 338232

URL: http://llvm.org/viewvc/llvm-project?rev=338232=rev
Log:
[clang-format] Indent after breaking Javadoc annotated line

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

Modified:
cfe/trunk/lib/Format/BreakableToken.cpp
cfe/trunk/lib/Format/BreakableToken.h
cfe/trunk/lib/Format/ContinuationIndenter.cpp
cfe/trunk/lib/Format/Format.cpp
cfe/trunk/unittests/Format/FormatTestComments.cpp
cfe/trunk/unittests/Format/FormatTestJS.cpp

Modified: cfe/trunk/lib/Format/BreakableToken.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/BreakableToken.cpp?rev=338232=338231=338232=diff
==
--- cfe/trunk/lib/Format/BreakableToken.cpp (original)
+++ cfe/trunk/lib/Format/BreakableToken.cpp Mon Jul 30 01:45:45 2018
@@ -235,6 +235,7 @@ BreakableToken::Split BreakableStringLit
 
 void BreakableStringLiteral::insertBreak(unsigned LineIndex,
  unsigned TailOffset, Split Split,
+ unsigned ContentIndent,
  WhitespaceManager ) const 
{
   Whitespaces.replaceWhitespaceInToken(
   Tok, Prefix.size() + TailOffset + Split.first, Split.second, Postfix,
@@ -510,8 +511,33 @@ unsigned BreakableBlockComment::getConte
   return std::max(0, ContentColumn[LineIndex]);
 }
 
+const llvm::StringSet<>
+BreakableBlockComment::ContentIndentingJavadocAnnotations = {
+"@param", "@return", "@returns", "@throws",  "@type", "@template",
+"@see",   "@deprecated", "@define",  "@exports", "@mods",
+};
+
+unsigned BreakableBlockComment::getContentIndent(unsigned LineIndex) const {
+  if (Style.Language != FormatStyle::LK_Java &&
+  Style.Language != FormatStyle::LK_JavaScript)
+return 0;
+  // The content at LineIndex 0 of a comment like:
+  // /** line 0 */
+  // is "* line 0", so we need to skip over the decoration in that case.
+  StringRef ContentWithNoDecoration = Content[LineIndex];
+  if (LineIndex == 0 && ContentWithNoDecoration.startswith("*")) {
+ContentWithNoDecoration = ContentWithNoDecoration.substr(1).ltrim(Blanks);
+  }
+  StringRef FirstWord = ContentWithNoDecoration.substr(
+  0, ContentWithNoDecoration.find_first_of(Blanks));
+  if (ContentIndentingJavadocAnnotations.find(FirstWord) !=
+  ContentIndentingJavadocAnnotations.end())
+return Style.ContinuationIndentWidth;
+  return 0;
+}
+
 void BreakableBlockComment::insertBreak(unsigned LineIndex, unsigned 
TailOffset,
-Split Split,
+Split Split, unsigned ContentIndent,
 WhitespaceManager ) const {
   StringRef Text = Content[LineIndex].substr(TailOffset);
   StringRef Prefix = Decoration;
@@ -532,10 +558,14 @@ void BreakableBlockComment::insertBreak(
   Text.data() - tokenAt(LineIndex).TokenText.data() + Split.first;
   unsigned CharsToRemove = Split.second;
   assert(LocalIndentAtLineBreak >= Prefix.size());
+  std::string PrefixWithTrailingIndent = Prefix;
+  for (unsigned I = 0; I < ContentIndent; ++I)
+PrefixWithTrailingIndent += " ";
   Whitespaces.replaceWhitespaceInToken(
-  tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "", Prefix,
-  InPPDirective, /*Newlines=*/1,
-  /*Spaces=*/LocalIndentAtLineBreak - Prefix.size());
+  tokenAt(LineIndex), BreakOffsetInToken, CharsToRemove, "",
+  PrefixWithTrailingIndent, InPPDirective, /*Newlines=*/1,
+  /*Spaces=*/LocalIndentAtLineBreak + ContentIndent -
+  PrefixWithTrailingIndent.size());
 }
 
 BreakableToken::Split
@@ -543,8 +573,17 @@ BreakableBlockComment::getReflowSplit(un
   llvm::Regex ) const {
   if (!mayReflow(LineIndex, CommentPragmasRegex))
 return Split(StringRef::npos, 0);
-
+  
+  // If we're reflowing into a line with content indent, only reflow the next
+  // line if its starting whitespace matches the content indent.
   size_t Trimmed = Content[LineIndex].find_first_not_of(Blanks);
+  if (LineIndex) {
+unsigned PreviousContentIndent = getContentIndent(LineIndex - 1);
+if (PreviousContentIndent && Trimmed != StringRef::npos &&
+Trimmed != PreviousContentIndent)
+  return Split(StringRef::npos, 0);
+  }
+
   return Split(0, Trimmed != StringRef::npos ? Trimmed : 0);
 }
 
@@ -583,7 +622,8 @@ void BreakableBlockComment::adaptStartOf
   // break length are the same.
   size_t BreakLength = Lines[0].substr(1).find_first_not_of(Blanks);
   if (BreakLength != StringRef::npos)
-insertBreak(LineIndex, 0, Split(1, BreakLength), Whitespaces);
+ 

r337899 - [clang-format ]Extend IncludeCategories regex documentation

2018-07-25 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Wed Jul 25 03:21:47 2018
New Revision: 337899

URL: http://llvm.org/viewvc/llvm-project?rev=337899=rev
Log:
[clang-format ]Extend IncludeCategories regex documentation

Summary:
Extend the Clang-Format IncludeCategories documentation by adding a link to the 
supported regular expression standard (POSIX).
And extenting the example with a system header regex.
[[ https://bugs.llvm.org/show_bug.cgi?id=35041 | bug 35041]]

Contributed by WimLeflere!

Reviewers: krasimir, Typz

Reviewed By: krasimir

Subscribers: cfe-commits

Differential Revision: https://reviews.llvm.org/D48827

Modified:
cfe/trunk/docs/ClangFormatStyleOptions.rst
cfe/trunk/docs/tools/dump_format_style.py
cfe/trunk/include/clang/Format/Format.h
cfe/trunk/include/clang/Tooling/Inclusions/IncludeStyle.h

Modified: cfe/trunk/docs/ClangFormatStyleOptions.rst
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/ClangFormatStyleOptions.rst?rev=337899=337898=337899=diff
==
--- cfe/trunk/docs/ClangFormatStyleOptions.rst (original)
+++ cfe/trunk/docs/ClangFormatStyleOptions.rst Wed Jul 25 03:21:47 2018
@@ -1280,6 +1280,10 @@ the configuration (without a prefix: ``A
   Regular expressions denoting the different ``#include`` categories
   used for ordering ``#includes``.
 
+  `POSIX extended
+  `_
+  regular expressions are supported.
+
   These regular expressions are matched against the filename of an include
   (including the <> or "") in order. The value belonging to the first
   matching regular expression is assigned and ``#includes`` are sorted first
@@ -1302,6 +1306,8 @@ the configuration (without a prefix: ``A
 Priority:2
   - Regex:   '^(<|"(gtest|gmock|isl|json)/)'
 Priority:3
+  - Regex:   '<[[:alnum:].]+>'
+Priority:4
   - Regex:   '.*'
 Priority:1
 

Modified: cfe/trunk/docs/tools/dump_format_style.py
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/tools/dump_format_style.py?rev=337899=337898=337899=diff
==
--- cfe/trunk/docs/tools/dump_format_style.py (original)
+++ cfe/trunk/docs/tools/dump_format_style.py Wed Jul 25 03:21:47 2018
@@ -10,6 +10,7 @@ import urllib2
 
 CLANG_DIR = os.path.join(os.path.dirname(__file__), '../..')
 FORMAT_STYLE_FILE = os.path.join(CLANG_DIR, 'include/clang/Format/Format.h')
+INCLUDE_STYLE_FILE = os.path.join(CLANG_DIR, 
'include/clang/Tooling/Inclusions/IncludeStyle.h')
 DOC_FILE = os.path.join(CLANG_DIR, 'docs/ClangFormatStyleOptions.rst')
 
 
@@ -115,7 +116,7 @@ def read_options(header):
   for line in header:
 line = line.strip()
 if state == State.BeforeStruct:
-  if line == 'struct FormatStyle {':
+  if line == 'struct FormatStyle {' or line == 'struct IncludeStyle {':
 state = State.InStruct
 elif state == State.InStruct:
   if line.startswith('///'):
@@ -188,6 +189,7 @@ def read_options(header):
   return options
 
 options = read_options(open(FORMAT_STYLE_FILE))
+options += read_options(open(INCLUDE_STYLE_FILE))
 
 options = sorted(options, key=lambda x: x.name)
 options_text = '\n\n'.join(map(str, options))

Modified: cfe/trunk/include/clang/Format/Format.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Format/Format.h?rev=337899=337898=337899=diff
==
--- cfe/trunk/include/clang/Format/Format.h (original)
+++ cfe/trunk/include/clang/Format/Format.h Wed Jul 25 03:21:47 2018
@@ -1296,7 +1296,7 @@ struct FormatStyle {
   /// If ``Never``, lays out Objective-C protocol conformance list items
   /// onto individual lines whenever they go over ``ColumnLimit``.
   ///
-  /// \code
+  /// \code{.objc}
   ///Always (or Auto, if BinPackParameters=true):
   ///@interface c () <
   ///c, c,

Modified: cfe/trunk/include/clang/Tooling/Inclusions/IncludeStyle.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/include/clang/Tooling/Inclusions/IncludeStyle.h?rev=337899=337898=337899=diff
==
--- cfe/trunk/include/clang/Tooling/Inclusions/IncludeStyle.h (original)
+++ cfe/trunk/include/clang/Tooling/Inclusions/IncludeStyle.h Wed Jul 25 
03:21:47 2018
@@ -67,6 +67,10 @@ struct IncludeStyle {
   /// Regular expressions denoting the different ``#include`` categories
   /// used for ordering ``#includes``.
   ///
+  /// `POSIX extended
+  /// 
`_
+  /// regular expressions are supported.
+  ///
   /// These regular expressions are matched against the filename of an include
   /// (including the <> or "") in order. The value 

r335978 - [clang-format] Support additional common functions for text proto formatting

2018-06-29 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Fri Jun 29 07:25:25 2018
New Revision: 335978

URL: http://llvm.org/viewvc/llvm-project?rev=335978=rev
Log:
[clang-format] Support additional common functions for text proto formatting

Summary: This adds a few more common function names expecting a text proto 
argument.

Reviewers: djasper

Reviewed By: djasper

Subscribers: cfe-commits

Differential Revision: https://reviews.llvm.org/D48760

Modified:
cfe/trunk/lib/Format/Format.cpp

Modified: cfe/trunk/lib/Format/Format.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/Format.cpp?rev=335978=335977=335978=diff
==
--- cfe/trunk/lib/Format/Format.cpp (original)
+++ cfe/trunk/lib/Format/Format.cpp Fri Jun 29 07:25:25 2018
@@ -775,8 +775,11 @@ FormatStyle getGoogleStyle(FormatStyle::
   },
   /*EnclosingFunctionNames=*/
   {
-  "PARSE_TEXT_PROTO",
   "EqualsProto",
+  "EquivToProto",
+  "PARSE_TEST_PROTO",
+  "PARSE_TEXT_PROTO",
+  "ParseTextOrDie",
   },
   /*CanonicalDelimiter=*/"",
   /*BasedOnStyle=*/"google",


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r335876 - [clang-format] Do not format raw string literals inside a recognized function with a non-recognized delimiter

2018-06-28 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Thu Jun 28 09:58:24 2018
New Revision: 335876

URL: http://llvm.org/viewvc/llvm-project?rev=335876=rev
Log:
[clang-format] Do not format raw string literals inside a recognized function 
with a non-recognized delimiter

Summary:
This stops clang-format from touching raw string contents with unrecognized 
delimiters inside recognized functions.
Unrecognized delimiters signal that the string might be special.

Subscribers: cfe-commits

Differential Revision: https://reviews.llvm.org/D48728

Modified:
cfe/trunk/lib/Format/ContinuationIndenter.cpp
cfe/trunk/unittests/Format/FormatTestRawStrings.cpp

Modified: cfe/trunk/lib/Format/ContinuationIndenter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/ContinuationIndenter.cpp?rev=335876=335875=335876=diff
==
--- cfe/trunk/lib/Format/ContinuationIndenter.cpp (original)
+++ cfe/trunk/lib/Format/ContinuationIndenter.cpp Thu Jun 28 09:58:24 2018
@@ -1648,7 +1648,7 @@ ContinuationIndenter::getRawStringStyle(
   if (!Delimiter)
 return None;
   auto RawStringStyle = RawStringFormats.getDelimiterStyle(*Delimiter);
-  if (!RawStringStyle)
+  if (!RawStringStyle && Delimiter->empty())
 RawStringStyle = RawStringFormats.getEnclosingFunctionStyle(
 getEnclosingFunctionName(Current));
   if (!RawStringStyle)

Modified: cfe/trunk/unittests/Format/FormatTestRawStrings.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestRawStrings.cpp?rev=335876=335875=335876=diff
==
--- cfe/trunk/unittests/Format/FormatTestRawStrings.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestRawStrings.cpp Thu Jun 28 09:58:24 2018
@@ -862,6 +862,32 @@ int f() {
 Style));
 }
 
+TEST_F(FormatTestRawStrings,
+   DoNotFormatUnrecognizedDelimitersInRecognizedFunctions) {
+  FormatStyle Style = getRawStringPbStyleWithColumns(60);
+  Style.RawStringFormats[0].EnclosingFunctions.push_back(
+  "EqualsProto");
+  // EqualsProto is a recognized function, but the Raw delimiter is
+  // unrecognized. Do not touch the string in this case, since it might be
+  // special.
+  expect_eq(R"test(
+void f() {
+  a(b, EqualsProto(R"Raw(
+item {
+  key: value
+}
+)Raw"));
+})test",
+format(R"test(
+void f() {
+  a(b, EqualsProto(R"Raw(
+item {
+  key: value
+}
+)Raw"));
+})test",
+   Style));
+}
 
 } // end namespace
 } // end namespace format


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r335595 - [clang-format] Enable text proto formatting in common functions

2018-06-26 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Tue Jun 26 05:00:14 2018
New Revision: 335595

URL: http://llvm.org/viewvc/llvm-project?rev=335595=rev
Log:
[clang-format] Enable text proto formatting in common functions

Subscribers: cfe-commits

Differential Revision: https://reviews.llvm.org/D48363

Modified:
cfe/trunk/lib/Format/Format.cpp

Modified: cfe/trunk/lib/Format/Format.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/Format.cpp?rev=335595=335594=335595=diff
==
--- cfe/trunk/lib/Format/Format.cpp (original)
+++ cfe/trunk/lib/Format/Format.cpp Tue Jun 26 05:00:14 2018
@@ -774,7 +774,10 @@ FormatStyle getGoogleStyle(FormatStyle::
   "PROTO",
   },
   /*EnclosingFunctionNames=*/
-  {},
+  {
+  "PARSE_TEXT_PROTO",
+  "EqualsProto",
+  },
   /*CanonicalDelimiter=*/"",
   /*BasedOnStyle=*/"google",
   },


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r335459 - [clang-format] Keep @message together in text protos

2018-06-25 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Mon Jun 25 05:43:12 2018
New Revision: 335459

URL: http://llvm.org/viewvc/llvm-project?rev=335459=rev
Log:
[clang-format] Keep @message together in text protos

Summary:
In C++ code snippets of the form `@field` are common. This makes clang-format
keep them together in text protos, whereas before it would break them.

Subscribers: cfe-commits

Differential Revision: https://reviews.llvm.org/D48543

Modified:
cfe/trunk/lib/Format/ContinuationIndenter.cpp
cfe/trunk/lib/Format/TokenAnnotator.cpp
cfe/trunk/unittests/Format/FormatTestTextProto.cpp

Modified: cfe/trunk/lib/Format/ContinuationIndenter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/ContinuationIndenter.cpp?rev=335459=335458=335459=diff
==
--- cfe/trunk/lib/Format/ContinuationIndenter.cpp (original)
+++ cfe/trunk/lib/Format/ContinuationIndenter.cpp Mon Jun 25 05:43:12 2018
@@ -379,7 +379,8 @@ bool ContinuationIndenter::mustBreak(con
   if (Current.is(TT_ObjCMethodExpr) && !Previous.is(TT_SelectorName) &&
   State.Line->startsWith(TT_ObjCMethodSpecifier))
 return true;
-  if (Current.is(TT_SelectorName) && State.Stack.back().ObjCSelectorNameFound 
&&
+  if (Current.is(TT_SelectorName) && !Previous.is(tok::at) &&
+  State.Stack.back().ObjCSelectorNameFound &&
   State.Stack.back().BreakBeforeParameter)
 return true;
 

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=335459=335458=335459=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Mon Jun 25 05:43:12 2018
@@ -2949,15 +2949,32 @@ bool TokenAnnotator::mustBreakBefore(con
   //
   // Be careful to exclude the case  [proto.ext] { ... } since the `]` is
   // the TT_SelectorName there, but we don't want to break inside the brackets.
+  //
+  // Another edge case is @submessage { key: value }, which is a common
+  // substitution placeholder. In this case we want to keep `@` and 
`submessage`
+  // together.
+  //
   // We ensure elsewhere that extensions are always on their own line.
   if ((Style.Language == FormatStyle::LK_Proto ||
Style.Language == FormatStyle::LK_TextProto) &&
   Right.is(TT_SelectorName) && !Right.is(tok::r_square) && Right.Next) {
+// Keep `@submessage` together in:
+// @submessage { key: value }
+if (Right.Previous && Right.Previous->is(tok::at))
+  return false;
 // Look for the scope opener after selector in cases like:
 // selector { ...
 // selector: { ...
-FormatToken *LBrace =
-Right.Next->is(tok::colon) ? Right.Next->Next : Right.Next;
+// selector: @base { ...
+FormatToken *LBrace = Right.Next;
+if (LBrace && LBrace->is(tok::colon)) {
+  LBrace = LBrace->Next;
+  if (LBrace && LBrace->is(tok::at)) {
+LBrace = LBrace->Next;
+if (LBrace)
+  LBrace = LBrace->Next;
+  }
+}
 if (LBrace &&
 // The scope opener is one of {, [, <:
 // selector { ... }

Modified: cfe/trunk/unittests/Format/FormatTestTextProto.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestTextProto.cpp?rev=335459=335458=335459=diff
==
--- cfe/trunk/unittests/Format/FormatTestTextProto.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestTextProto.cpp Mon Jun 25 05:43:12 2018
@@ -717,5 +717,23 @@ TEST_F(FormatTestTextProto, FormatsComme
"# endfile comment");
 }
 
+TEST_F(FormatTestTextProto, KeepsAmpersandsNextToKeys) {
+  verifyFormat("@tmpl { field: 1 }");
+  verifyFormat("@placeholder: 1");
+  verifyFormat("@name <>");
+  verifyFormat("submessage: @base { key: value }");
+  verifyFormat("submessage: @base {\n"
+   "  key: value\n"
+   "  item: {}\n"
+   "}");
+  verifyFormat("submessage: {\n"
+   "  msg: @base {\n"
+   "yolo: {}\n"
+   "key: value\n"
+   "  }\n"
+   "  key: value\n"
+   "}");
+}
+
 } // end namespace tooling
 } // end namespace clang


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r335449 - [clang-format] Fix end-of-file comments text proto formatting

2018-06-25 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Mon Jun 25 04:08:24 2018
New Revision: 335449

URL: http://llvm.org/viewvc/llvm-project?rev=335449=rev
Log:
[clang-format] Fix end-of-file comments text proto formatting

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

Modified:
cfe/trunk/lib/Format/UnwrappedLineParser.cpp
cfe/trunk/unittests/Format/FormatTestTextProto.cpp

Modified: cfe/trunk/lib/Format/UnwrappedLineParser.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/UnwrappedLineParser.cpp?rev=335449=335448=335449=diff
==
--- cfe/trunk/lib/Format/UnwrappedLineParser.cpp (original)
+++ cfe/trunk/lib/Format/UnwrappedLineParser.cpp Mon Jun 25 04:08:24 2018
@@ -303,6 +303,18 @@ void UnwrappedLineParser::parseFile() {
   else
 parseLevel(/*HasOpeningBrace=*/false);
   // Make sure to format the remaining tokens.
+  //
+  // LK_TextProto is special since its top-level is parsed as the body of a
+  // braced list, which does not necessarily have natural line separators such
+  // as a semicolon. Comments after the last entry that have been determined to
+  // not belong to that line, as in:
+  //   key: value
+  //   // endfile comment
+  // do not have a chance to be put on a line of their own until this point.
+  // Here we add this newline before end-of-file comments.
+  if (Style.Language == FormatStyle::LK_TextProto &&
+  !CommentsBeforeNextToken.empty())
+addUnwrappedLine();
   flushComments(true);
   addUnwrappedLine();
 }

Modified: cfe/trunk/unittests/Format/FormatTestTextProto.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestTextProto.cpp?rev=335449=335448=335449=diff
==
--- cfe/trunk/unittests/Format/FormatTestTextProto.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestTextProto.cpp Mon Jun 25 04:08:24 2018
@@ -700,5 +700,22 @@ TEST_F(FormatTestTextProto, PreventBreak
   "}");
 }
 
+TEST_F(FormatTestTextProto, FormatsCommentsAtEndOfFile) {
+  verifyFormat("key: value\n"
+   "# endfile comment");
+  verifyFormat("key: value\n"
+   "// endfile comment");
+  verifyFormat("key: value\n"
+   "// endfile comment 1\n"
+   "// endfile comment 2");
+  verifyFormat("submessage { key: value }\n"
+   "# endfile comment");
+  verifyFormat("submessage <\n"
+   "  key: value\n"
+   "  item {}\n"
+   ">\n"
+   "# endfile comment");
+}
+
 } // end namespace tooling
 } // end namespace clang


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r334527 - [clang-format] Fix crash while reflowing backslash in comments

2018-06-12 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Tue Jun 12 12:33:15 2018
New Revision: 334527

URL: http://llvm.org/viewvc/llvm-project?rev=334527=rev
Log:
[clang-format] Fix crash while reflowing backslash in comments

Summary:
The added test case was currently crashing with an assertion:
```
krasimir@krasimir> cat test.cc  

~
// How to run:
// b run \
// 
rrr 
\
//  -- --output_directory=""
krasimir@krasimir> ~/work/llvm-build/bin/clang-format test.cc   

~
clang-format: 
/usr/local/google/home/krasimir/work/llvm/tools/clang/lib/Format/WhitespaceManager.cpp:117:
 void clang::format::WhitespaceManager::calculateLineBreakInformation(): 
Assertion `PreviousOriginalWhitespaceEndOffset <= 
OriginalWhitespaceStartOffset' failed.
```
The root cause was that BreakableToken was not considering the case of a reflow 
between an unescaped newline in a line comment.

Subscribers: cfe-commits

Differential Revision: https://reviews.llvm.org/D48089

Modified:
cfe/trunk/lib/Format/BreakableToken.cpp
cfe/trunk/unittests/Format/FormatTestComments.cpp

Modified: cfe/trunk/lib/Format/BreakableToken.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/BreakableToken.cpp?rev=334527=334526=334527=diff
==
--- cfe/trunk/lib/Format/BreakableToken.cpp (original)
+++ cfe/trunk/lib/Format/BreakableToken.cpp Tue Jun 12 12:33:15 2018
@@ -789,16 +789,47 @@ BreakableComment::Split BreakableLineCom
 
 void BreakableLineCommentSection::reflow(unsigned LineIndex,
  WhitespaceManager ) const 
{
-  // Reflow happens between tokens. Replace the whitespace between the
-  // tokens by the empty string.
-  Whitespaces.replaceWhitespace(
-  *Tokens[LineIndex], /*Newlines=*/0, /*Spaces=*/0,
-  /*StartOfTokenColumn=*/StartColumn, /*InPPDirective=*/false);
+  if (LineIndex > 0 && Tokens[LineIndex] != Tokens[LineIndex - 1]) {
+// Reflow happens between tokens. Replace the whitespace between the
+// tokens by the empty string.
+Whitespaces.replaceWhitespace(
+*Tokens[LineIndex], /*Newlines=*/0, /*Spaces=*/0,
+/*StartOfTokenColumn=*/StartColumn, /*InPPDirective=*/false);
+  } else if (LineIndex > 0) {
+// In case we're reflowing after the '\' in:
+//
+//   // line comment \
+//   // line 2
+//
+// the reflow happens inside the single comment token (it is a single line
+// comment with an unescaped newline).
+// Replace the whitespace between the '\' and '//' with the empty string.
+//
+// Offset points to after the '\' relative to start of the token.
+unsigned Offset = Lines[LineIndex - 1].data() +
+  Lines[LineIndex - 1].size() -
+  tokenAt(LineIndex - 1).TokenText.data();
+// WhitespaceLength is the number of chars between the '\' and the '//' on
+// the next line.
+unsigned WhitespaceLength =
+Lines[LineIndex].data() - tokenAt(LineIndex).TokenText.data() - Offset;
+Whitespaces.replaceWhitespaceInToken(*Tokens[LineIndex],
+ Offset,
+ /*ReplaceChars=*/WhitespaceLength,
+ /*PreviousPostfix=*/"",
+ /*CurrentPrefix=*/"",
+ /*InPPDirective=*/false,
+ /*Newlines=*/0,
+ /*Spaces=*/0);
+
+  }
   // Replace the indent and prefix of the token with the reflow prefix.
+  unsigned Offset =
+  Lines[LineIndex].data() - tokenAt(LineIndex).TokenText.data();
   unsigned WhitespaceLength =
-  Content[LineIndex].data() - tokenAt(LineIndex).TokenText.data();
+  Content[LineIndex].data() - Lines[LineIndex].data();
   Whitespaces.replaceWhitespaceInToken(*Tokens[LineIndex],
-   /*Offset=*/0,
+   Offset,
/*ReplaceChars=*/WhitespaceLength,
/*PreviousPostfix=*/"",
/*CurrentPrefix=*/ReflowPrefix,

Modified: cfe/trunk/unittests/Format/FormatTestComments.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestComments.cpp?rev=334527=334526=334527=diff
==
--- cfe/trunk/unittests/Format/FormatTestComments.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestComments.cpp Tue Jun 12 12:33:15 2018

r334517 - [clang-format] Discourage breaks in submessage entries, hard rule

2018-06-12 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Tue Jun 12 10:26:31 2018
New Revision: 334517

URL: http://llvm.org/viewvc/llvm-project?rev=334517=rev
Log:
[clang-format] Discourage breaks in submessage entries, hard rule

Summary:
Currently clang-format allows this for text protos:
```
submessage:
{ key: 'aa' }
```
when it is under the column limit and when putting it all on one line exceeds 
the column limit.

This is not a very intuitive formatting, so I'd prefer having
```
submessage: {
  key: 'aa'
}
```
instead, even if it takes one line more.

This patch prevents clang-format from inserting a break between `: {` and 
similar cases.

Reviewers: djasper, sammccall

Reviewed By: sammccall

Subscribers: cfe-commits

Differential Revision: https://reviews.llvm.org/D48063

Modified:
cfe/trunk/lib/Format/TokenAnnotator.cpp
cfe/trunk/unittests/Format/FormatTestProto.cpp
cfe/trunk/unittests/Format/FormatTestTextProto.cpp

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=334517=334516=334517=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Tue Jun 12 10:26:31 2018
@@ -3101,10 +3101,39 @@ bool TokenAnnotator::canBreakBefore(cons
   !Right.isOneOf(TT_CtorInitializerColon, TT_InlineASMColon))
 return false;
   if (Left.is(tok::colon) && Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)) {
-if ((Style.Language == FormatStyle::LK_Proto ||
- Style.Language == FormatStyle::LK_TextProto) &&
-!Style.AlwaysBreakBeforeMultilineStrings && Right.isStringLiteral())
-  return false;
+if (Style.Language == FormatStyle::LK_Proto ||
+Style.Language == FormatStyle::LK_TextProto) {
+  if (!Style.AlwaysBreakBeforeMultilineStrings && Right.isStringLiteral())
+return false;
+  // Prevent cases like:
+  //
+  // submessage:
+  // { key: valu }
+  //
+  // when the snippet does not fit into one line.
+  // Prefer:
+  //
+  // submessage: {
+  //   key: valu
+  // }
+  //
+  // instead, even if it is longer by one line.
+  //
+  // Note that this allows allows the "{" to go over the column limit
+  // when the column limit is just between ":" and "{", but that does
+  // not happen too often and alternative formattings in this case are
+  // not much better.
+  //
+  // The code covers the cases:
+  //
+  // submessage: { ... }
+  // submessage: < ... >
+  // repeated: [ ... ]
+  if (((Right.is(tok::l_brace) || Right.is(tok::less)) &&
+   Right.is(TT_DictLiteral)) ||
+  Right.is(TT_ArrayInitializerLSquare))
+return false;
+}
 return true;
   }
   if (Right.is(tok::r_square) && Right.MatchingParen &&

Modified: cfe/trunk/unittests/Format/FormatTestProto.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestProto.cpp?rev=334517=334516=334517=diff
==
--- cfe/trunk/unittests/Format/FormatTestProto.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestProto.cpp Tue Jun 12 10:26:31 2018
@@ -624,5 +624,34 @@ TEST_F(FormatTestProto, BreaksEntriesOfS
"}");
 }
 
+TEST_F(FormatTestProto, PreventBreaksBetweenKeyAndSubmessages) {
+  verifyFormat("option (MyProto.options) = {\n"
+   "  submessage: {\n"
+   "key: 'a'\n"
+   "  }\n"
+   "}");
+  verifyFormat("option (MyProto.options) = {\n"
+   "  submessage {\n"
+   "key: 'a'\n"
+   "  }\n"
+   "}");
+  verifyFormat("option (MyProto.options) = {\n"
+   "  submessage: <\n"
+   "key: 'a'\n"
+   "  >\n"
+   "}");
+  verifyFormat("option (MyProto.options) = {\n"
+   "  submessage <\n"
+   "key: 'a'\n"
+   "  >\n"
+   "}");
+  verifyFormat("option (MyProto.options) = {\n"
+   "  repeatedd: [\n"
+   "'ey'\n"
+   "  ]\n"
+   "}");
+}
+
+
 } // end namespace tooling
 } // end namespace clang

Modified: cfe/trunk/unittests/Format/FormatTestTextProto.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestTextProto.cpp?rev=334517=334516=334517=diff
==
--- cfe/trunk/unittests/Format/FormatTestTextProto.cpp (original)
+++ 

r334401 - [clang-format] text protos: put entries on separate lines if there is a submessage

2018-06-11 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Mon Jun 11 05:53:25 2018
New Revision: 334401

URL: http://llvm.org/viewvc/llvm-project?rev=334401=rev
Log:
[clang-format] text protos: put entries on separate lines if there is a 
submessage

Summary:
This patch updates clang-format text protos to put entries of a submessage into 
separate lines if the submessage contains at least two entries and contains at 
least one submessage entry.

For example, the entries here are kept on separate lines even if putting them 
on a single line would be under the column limit:
```
message: {
  entry: 1
  submessage: { key: value }
}
```

Messages containing a single submessage or several scalar entries can still be 
put on one line if they fit:
```
message { submessage { key: value } }
message { x: 1 y: 2 z: 3 }
```

Reviewers: sammccall

Reviewed By: sammccall

Subscribers: klimek, cfe-commits

Differential Revision: https://reviews.llvm.org/D46757

Modified:
cfe/trunk/lib/Format/TokenAnnotator.cpp
cfe/trunk/unittests/Format/FormatTestProto.cpp
cfe/trunk/unittests/Format/FormatTestRawStrings.cpp
cfe/trunk/unittests/Format/FormatTestTextProto.cpp

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=334401=334400=334401=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Mon Jun 11 05:53:25 2018
@@ -2924,6 +2924,74 @@ bool TokenAnnotator::mustBreakBefore(con
   if (Right.is(TT_ProtoExtensionLSquare))
 return true;
 
+  // In text proto instances if a submessage contains at least 2 entries and at
+  // least one of them is a submessage, like A { ... B { ... } ... },
+  // put all of the entries of A on separate lines by forcing the selector of
+  // the submessage B to be put on a newline.
+  //
+  // Example: these can stay on one line:
+  // a { scalar_1: 1 scalar_2: 2 }
+  // a { b { key: value } }
+  //
+  // and these entries need to be on a new line even if putting them all in one
+  // line is under the column limit:
+  // a {
+  //   scalar: 1
+  //   b { key: value }
+  // }
+  //
+  // We enforce this by breaking before a submessage field that has previous
+  // siblings, *and* breaking before a field that follows a submessage field.
+  //
+  // Be careful to exclude the case  [proto.ext] { ... } since the `]` is
+  // the TT_SelectorName there, but we don't want to break inside the brackets.
+  // We ensure elsewhere that extensions are always on their own line.
+  if ((Style.Language == FormatStyle::LK_Proto ||
+   Style.Language == FormatStyle::LK_TextProto) &&
+  Right.is(TT_SelectorName) && !Right.is(tok::r_square) && Right.Next) {
+// Look for the scope opener after selector in cases like:
+// selector { ...
+// selector: { ...
+FormatToken *LBrace =
+Right.Next->is(tok::colon) ? Right.Next->Next : Right.Next;
+if (LBrace &&
+// The scope opener is one of {, [, <:
+// selector { ... }
+// selector [ ... ]
+// selector < ... >
+//
+// In case of selector { ... }, the l_brace is TT_DictLiteral.
+// In case of an empty selector {}, the l_brace is not TT_DictLiteral,
+// so we check for immediately following r_brace.
+((LBrace->is(tok::l_brace) &&
+  (LBrace->is(TT_DictLiteral) ||
+   (LBrace->Next && LBrace->Next->is(tok::r_brace ||
+ LBrace->is(TT_ArrayInitializerLSquare) || LBrace->is(tok::less))) {
+  // If Left.ParameterCount is 0, then this submessage entry is not the
+  // first in its parent submessage, and we want to break before this 
entry.
+  // If Left.ParameterCount is greater than 0, then its parent submessage
+  // might contain 1 or more entries and we want to break before this entry
+  // if it contains at least 2 entries. We deal with this case later by
+  // detecting and breaking before the next entry in the parent submessage.
+  if (Left.ParameterCount == 0)
+return true;
+  // However, if this submessage is the first entry in its parent
+  // submessage, Left.ParameterCount might be 1 in some cases.
+  // We deal with this case later by detecting an entry
+  // following a closing paren of this submessage.
+}
+
+// If this is an entry immediately following a submessage, it will be
+// preceded by a closing paren of that submessage, like in:
+// left---.  .---right
+//v  v
+// sub: { ... } key: value
+// If there was a comment between `}` an `key` above, then `key` would be
+// put on a new line anyways.
+if (Left.isOneOf(tok::r_brace, tok::greater, tok::r_square))
+  return true;
+  }
+
   return false;
 }
 

Modified: cfe/trunk/unittests/Format/FormatTestProto.cpp
URL: 

r334179 - [clang-format] Consider tok::hashhash in python-style comments

2018-06-07 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Thu Jun  7 02:46:24 2018
New Revision: 334179

URL: http://llvm.org/viewvc/llvm-project?rev=334179=rev
Log:
[clang-format] Consider tok::hashhash in python-style comments

Summary: We were missing the case when python-style comments in text protos 
start with `##`.

Subscribers: cfe-commits

Differential Revision: https://reviews.llvm.org/D47870

Modified:
cfe/trunk/lib/Format/BreakableToken.cpp
cfe/trunk/lib/Format/FormatTokenLexer.cpp
cfe/trunk/unittests/Format/FormatTestTextProto.cpp

Modified: cfe/trunk/lib/Format/BreakableToken.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/BreakableToken.cpp?rev=334179=334178=334179=diff
==
--- cfe/trunk/lib/Format/BreakableToken.cpp (original)
+++ cfe/trunk/lib/Format/BreakableToken.cpp Thu Jun  7 02:46:24 2018
@@ -44,7 +44,8 @@ static StringRef getLineCommentIndentPre
 const FormatStyle ) {
   static const char *const KnownCStylePrefixes[] = {"///<", "//!<", "///", 
"//",
 "//!"};
-  static const char *const KnownTextProtoPrefixes[] = {"//", "#"};
+  static const char *const KnownTextProtoPrefixes[] = {"//", "#", "##", "###",
+   ""};
   ArrayRef KnownPrefixes(KnownCStylePrefixes);
   if (Style.Language == FormatStyle::LK_TextProto)
 KnownPrefixes = KnownTextProtoPrefixes;

Modified: cfe/trunk/lib/Format/FormatTokenLexer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/FormatTokenLexer.cpp?rev=334179=334178=334179=diff
==
--- cfe/trunk/lib/Format/FormatTokenLexer.cpp (original)
+++ cfe/trunk/lib/Format/FormatTokenLexer.cpp Thu Jun  7 02:46:24 2018
@@ -334,7 +334,7 @@ void FormatTokenLexer::handleTemplateStr
 
 void FormatTokenLexer::tryParsePythonComment() {
   FormatToken *HashToken = Tokens.back();
-  if (HashToken->isNot(tok::hash))
+  if (!HashToken->isOneOf(tok::hash, tok::hashhash))
 return;
   // Turn the remainder of this line into a comment.
   const char *CommentBegin =

Modified: cfe/trunk/unittests/Format/FormatTestTextProto.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestTextProto.cpp?rev=334179=334178=334179=diff
==
--- cfe/trunk/unittests/Format/FormatTestTextProto.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestTextProto.cpp Thu Jun  7 02:46:24 2018
@@ -347,6 +347,28 @@ TEST_F(FormatTestTextProto, KeepsComment
": 3849");
 }
 
+TEST_F(FormatTestTextProto, UnderstandsHashHashComments) {
+  FormatStyle Style = getGoogleStyle(FormatStyle::LK_TextProto);
+  Style.ColumnLimit = 60; // To make writing tests easier.
+  EXPECT_EQ("aaa: 100\n"
+"##this is a double-hash comment.\n"
+"bb: 100\n"
+"## another double-hash comment.\n"
+"### a triple-hash comment\n"
+"cc: 200\n"
+" a quadriple-hash comment\n"
+"dd: 100\n",
+format("aaa: 100\n"
+   "##this is a double-hash comment.\n"
+   "bb: 100\n"
+   "## another double-hash comment.\n"
+   "### a triple-hash comment\n"
+   "cc: 200\n"
+   " a quadriple-hash comment\n"
+   "dd: 100\n",
+   Style));
+}
+
 TEST_F(FormatTestTextProto, FormatsExtensions) {
   verifyFormat("[type] { key: value }");
   verifyFormat("[type] {\n"


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r333092 - [clang-format] fix buildbots after r333085

2018-05-23 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Wed May 23 08:21:33 2018
New Revision: 333092

URL: http://llvm.org/viewvc/llvm-project?rev=333092=rev
Log:
[clang-format] fix buildbots after r333085

Old gcc versions don't like raw string literals in macros.

Modified:
cfe/trunk/unittests/Format/FormatTest.cpp

Modified: cfe/trunk/unittests/Format/FormatTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTest.cpp?rev=333092=333091=333092=diff
==
--- cfe/trunk/unittests/Format/FormatTest.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTest.cpp Wed May 23 08:21:33 2018
@@ -5524,53 +5524,52 @@ TEST_F(FormatTest, WrapsTemplateDeclarat
 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) {
   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
   Style.ColumnLimit = 60;
-  EXPECT_EQ(R"test(
-// Baseline - no comments.
-template <
-typename aa::value>
-void f() {})test",
-format(R"test(
-// Baseline - no comments.
-template <
-typename aa::value>
-void f() {})test", Style));
+  EXPECT_EQ("// Baseline - no comments.\n"
+"template <\n"
+"typename aa::value>\n"
+"void f() {}",
+format("// Baseline - no comments.\n"
+   "template <\n"
+   "typename 
aa::value>\n"
+   "void f() {}",
+   Style));
 
-  EXPECT_EQ(R"test(
-template <
-typename aa::value>  // trailing
-void f() {})test",
-format(R"test(
-template <
-typename aa::value> // trailing
-void f() {})test", Style));
+  EXPECT_EQ("template <\n"
+"typename aa::value>  // trailing\n"
+"void f() {}",
+format("template <\n"
+   "typename aa::value> // 
trailing\n"
+   "void f() {}",
+   Style));
 
-  EXPECT_EQ(R"test(
-template <
-typename aa::value> /* line */
-void f() {})test",
-format(R"test(
-template ::value>  /* line */
-void f() {})test", Style));
+  EXPECT_EQ(
+  "template <\n"
+  "typename aa::value> /* line */\n"
+  "void f() {}",
+  format("template ::value>  /* line 
*/\n"
+ "void f() {}",
+ Style));
 
-  EXPECT_EQ(R"test(
-template <
-typename aa::value>  // trailing
-   // multiline
-void f() {})test",
-format(R"test(
-template <
-typename aa::value> // trailing
-  // multiline
-void f() {})test", Style));
+  EXPECT_EQ(
+  "template <\n"
+  "typename aa::value>  // trailing\n"
+  "   // multiline\n"
+  "void f() {}",
+  format("template <\n"
+ "typename aa::value> // trailing\n"
+ "  // multiline\n"
+ "void f() {}",
+ Style));
 
-  EXPECT_EQ(R"test(
-template ::value>  // trailing lng
-void f() {})test",
-format(R"test(
-template <
-typename aa::value> // trailing lng
-void f() {})test", Style));
+  EXPECT_EQ(
+  "template ::value>  // trailing lng\n"
+  "void f() {}",
+  format(
+  "template <\n"
+  "typename aa::value> // trailing lng\n"
+  "void f() {}",
+  Style));
 }
 
 TEST_F(FormatTest, WrapsTemplateParameters) {


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r333085 - [clang-format] Break template declarations followed by comments

2018-05-23 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Wed May 23 07:18:19 2018
New Revision: 333085

URL: http://llvm.org/viewvc/llvm-project?rev=333085=rev
Log:
[clang-format] Break template declarations followed by comments

Summary:
This patch fixes two bugs in clang-format where the template wrapper doesn't 
skip over
comments causing a long template declaration to not be split into multiple 
lines.
These were latent and exposed by r332436.

Reviewers: sammccall

Reviewed By: sammccall

Subscribers: klimek, cfe-commits

Differential Revision: https://reviews.llvm.org/D47257

Modified:
cfe/trunk/lib/Format/ContinuationIndenter.cpp
cfe/trunk/unittests/Format/FormatTest.cpp

Modified: cfe/trunk/lib/Format/ContinuationIndenter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/ContinuationIndenter.cpp?rev=333085=333084=333085=diff
==
--- cfe/trunk/lib/Format/ContinuationIndenter.cpp (original)
+++ cfe/trunk/lib/Format/ContinuationIndenter.cpp Wed May 23 07:18:19 2018
@@ -405,7 +405,7 @@ bool ContinuationIndenter::mustBreak(con
   // If the template declaration spans multiple lines, force wrap before the
   // function/class declaration
   if (Previous.ClosesTemplateDeclaration &&
-  State.Stack.back().BreakBeforeParameter)
+  State.Stack.back().BreakBeforeParameter && Current.CanBreakBefore)
 return true;
 
   if (State.Column <= NewLineColumn)
@@ -804,7 +804,8 @@ unsigned ContinuationIndenter::addTokenO
!State.Stack.back().AvoidBinPacking) ||
   Previous.is(TT_BinaryOperator))
 State.Stack.back().BreakBeforeParameter = false;
-  if (Previous.isOneOf(TT_TemplateCloser, TT_JavaAnnotation) &&
+  if (PreviousNonComment &&
+  PreviousNonComment->isOneOf(TT_TemplateCloser, TT_JavaAnnotation) &&
   Current.NestingLevel == 0)
 State.Stack.back().BreakBeforeParameter = false;
   if (NextNonComment->is(tok::question) ||

Modified: cfe/trunk/unittests/Format/FormatTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTest.cpp?rev=333085=333084=333085=diff
==
--- cfe/trunk/unittests/Format/FormatTest.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTest.cpp Wed May 23 07:18:19 2018
@@ -5521,6 +5521,58 @@ TEST_F(FormatTest, WrapsTemplateDeclarat
NeverBreak);
 }
 
+TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) {
+  FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
+  Style.ColumnLimit = 60;
+  EXPECT_EQ(R"test(
+// Baseline - no comments.
+template <
+typename aa::value>
+void f() {})test",
+format(R"test(
+// Baseline - no comments.
+template <
+typename aa::value>
+void f() {})test", Style));
+
+  EXPECT_EQ(R"test(
+template <
+typename aa::value>  // trailing
+void f() {})test",
+format(R"test(
+template <
+typename aa::value> // trailing
+void f() {})test", Style));
+
+  EXPECT_EQ(R"test(
+template <
+typename aa::value> /* line */
+void f() {})test",
+format(R"test(
+template ::value>  /* line */
+void f() {})test", Style));
+
+  EXPECT_EQ(R"test(
+template <
+typename aa::value>  // trailing
+   // multiline
+void f() {})test",
+format(R"test(
+template <
+typename aa::value> // trailing
+  // multiline
+void f() {})test", Style));
+
+  EXPECT_EQ(R"test(
+template ::value>  // trailing lng
+void f() {})test",
+format(R"test(
+template <
+typename aa::value> // trailing lng
+void f() {})test", Style));
+}
+
 TEST_F(FormatTest, WrapsTemplateParameters) {
   FormatStyle Style = getLLVMStyle();
   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r332974 - [clang-format] Add a test case for crash

2018-05-22 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Tue May 22 04:44:03 2018
New Revision: 332974

URL: http://llvm.org/viewvc/llvm-project?rev=332974=rev
Log:
[clang-format] Add a test case for crash

Modified:
cfe/trunk/unittests/Format/FormatTest.cpp

Modified: cfe/trunk/unittests/Format/FormatTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTest.cpp?rev=332974=332973=332974=diff
==
--- cfe/trunk/unittests/Format/FormatTest.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTest.cpp Tue May 22 04:44:03 2018
@@ -6628,6 +6628,18 @@ TEST_F(FormatTest, IncorrectCodeUnbalanc
   verifyNoCrash("(/**/[:!] ?[).");
 }
 
+TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) {
+  // Found by oss-fuzz:
+  // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212
+  FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
+  Style.ColumnLimit = 60;
+  verifyNoCrash(
+  "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20"
+  "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20"
+  "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a",
+  Style);
+}
+
 TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
   verifyFormat("do {\n}");
   verifyFormat("do {\n}\n"


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r332961 - [clang-format] Fix crash in getLengthToMatchingParen

2018-05-22 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Tue May 22 02:46:55 2018
New Revision: 332961

URL: http://llvm.org/viewvc/llvm-project?rev=332961=rev
Log:
[clang-format] Fix crash in getLengthToMatchingParen

Summary:
Found by oss-fuzz:
https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212

Reviewers: bkramer

Subscribers: klimek, cfe-commits

Differential Revision: https://reviews.llvm.org/D47191

Modified:
cfe/trunk/lib/Format/ContinuationIndenter.cpp

Modified: cfe/trunk/lib/Format/ContinuationIndenter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/ContinuationIndenter.cpp?rev=332961=332960=332961=diff
==
--- cfe/trunk/lib/Format/ContinuationIndenter.cpp (original)
+++ cfe/trunk/lib/Format/ContinuationIndenter.cpp Tue May 22 02:46:55 2018
@@ -94,9 +94,9 @@ static unsigned getLengthToMatchingParen
   break;
 if (!End->Next->closesScope())
   continue;
-if (End->Next->MatchingParen->isOneOf(tok::l_brace,
-  TT_ArrayInitializerLSquare,
-  tok::less)) {
+if (End->Next->MatchingParen &&
+End->Next->MatchingParen->isOneOf(
+tok::l_brace, TT_ArrayInitializerLSquare, tok::less)) {
   const ParenState *State = FindParenState(End->Next->MatchingParen);
   if (State && State->BreakBeforeClosingBrace)
 break;


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r332225 - [clang-format] Continue after non-scope-closers in getLengthToMatchingParen

2018-05-14 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Mon May 14 03:33:40 2018
New Revision: 332225

URL: http://llvm.org/viewvc/llvm-project?rev=332225=rev
Log:
[clang-format] Continue after non-scope-closers in getLengthToMatchingParen

Summary:
This fixes a regression introduced by `r331857` where we stop the search for
the End token as soon as we hit a non-scope-closer, which prematurely stops 
before
semicolons for example, which should otherwise be considered as part of the 
unbreakable tail.

Subscribers: klimek, cfe-commits

Differential Revision: https://reviews.llvm.org/D46824

Modified:
cfe/trunk/lib/Format/ContinuationIndenter.cpp
cfe/trunk/unittests/Format/FormatTestObjC.cpp

Modified: cfe/trunk/lib/Format/ContinuationIndenter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/ContinuationIndenter.cpp?rev=332225=332224=332225=diff
==
--- cfe/trunk/lib/Format/ContinuationIndenter.cpp (original)
+++ cfe/trunk/lib/Format/ContinuationIndenter.cpp Mon May 14 03:33:40 2018
@@ -90,8 +90,10 @@ static unsigned getLengthToMatchingParen
 return MatchingStackIndex >= 0 ? [MatchingStackIndex] : nullptr;
   };
   for (; End->Next; End = End->Next) {
-if (End->Next->CanBreakBefore || !End->Next->closesScope())
+if (End->Next->CanBreakBefore)
   break;
+if (!End->Next->closesScope())
+  continue;
 if (End->Next->MatchingParen->isOneOf(tok::l_brace,
   TT_ArrayInitializerLSquare,
   tok::less)) {

Modified: cfe/trunk/unittests/Format/FormatTestObjC.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestObjC.cpp?rev=332225=332224=332225=diff
==
--- cfe/trunk/unittests/Format/FormatTestObjC.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestObjC.cpp Mon May 14 03:33:40 2018
@@ -1142,6 +1142,18 @@ TEST_F(FormatTestObjC, ObjCArrayLiterals
"  @\"aa\"\n"
"];\n");
 }
+
+TEST_F(FormatTestObjC, BreaksCallStatementWhereSemiJustOverTheLimit) {
+  Style.ColumnLimit = 60;
+  // If the statement starting with 'a = ...' is put on a single line, the ';'
+  // is at line 61.
+  verifyFormat("int f(int a) {\n"
+   "  a = [self aa:b\n"
+   " c:\n"
+   "ee:fddd];\n"
+   "}");
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r331857 - [clang-format] Respect BreakBeforeClosingBrace while calculating length

2018-05-09 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Wed May  9 02:02:11 2018
New Revision: 331857

URL: http://llvm.org/viewvc/llvm-project?rev=331857=rev
Log:
[clang-format] Respect BreakBeforeClosingBrace while calculating length

Summary:
This patch makes `getLengthToMatchingParen` respect the 
`BreakBeforeClosingBrace`
ParenState for matching scope closers. In order to distinguish between paren 
states
introduced by real vs. fake parens, I've added the token opening the ParensState
to that struct.

Reviewers: djasper

Reviewed By: djasper

Subscribers: klimek, cfe-commits

Differential Revision: https://reviews.llvm.org/D46519

Modified:
cfe/trunk/lib/Format/ContinuationIndenter.cpp
cfe/trunk/lib/Format/ContinuationIndenter.h
cfe/trunk/lib/Format/UnwrappedLineFormatter.cpp
cfe/trunk/unittests/Format/FormatTestProto.cpp
cfe/trunk/unittests/Format/FormatTestRawStrings.cpp
cfe/trunk/unittests/Format/FormatTestTextProto.cpp

Modified: cfe/trunk/lib/Format/ContinuationIndenter.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/ContinuationIndenter.cpp?rev=331857=331856=331857=diff
==
--- cfe/trunk/lib/Format/ContinuationIndenter.cpp (original)
+++ cfe/trunk/lib/Format/ContinuationIndenter.cpp Wed May  9 02:02:11 2018
@@ -35,12 +35,70 @@ static bool shouldIndentWrappedSelectorN
 
 // Returns the length of everything up to the first possible line break after
 // the ), ], } or > matching \c Tok.
-static unsigned getLengthToMatchingParen(const FormatToken ) {
+static unsigned getLengthToMatchingParen(const FormatToken ,
+ const std::vector ) 
{
+  // Normally whether or not a break before T is possible is calculated and
+  // stored in T.CanBreakBefore. Braces, array initializers and text proto
+  // messages like `key: < ... >` are an exception: a break is possible
+  // before a closing brace R if a break was inserted after the corresponding
+  // opening brace. The information about whether or not a break is needed
+  // before a closing brace R is stored in the ParenState field
+  // S.BreakBeforeClosingBrace where S is the state that R closes.
+  //
+  // In order to decide whether there can be a break before encountered right
+  // braces, this implementation iterates over the sequence of tokens and over
+  // the paren stack in lockstep, keeping track of the stack level which 
visited
+  // right braces correspond to in MatchingStackIndex.
+  //
+  // For example, consider:
+  // L. <- line number
+  // 1. {
+  // 2. {1},
+  // 3. {2},
+  // 4. {{3}}}
+  // ^ where we call this method with this token.
+  // The paren stack at this point contains 3 brace levels:
+  //  0. { at line 1, BreakBeforeClosingBrace: true
+  //  1. first { at line 4, BreakBeforeClosingBrace: false
+  //  2. second { at line 4, BreakBeforeClosingBrace: false,
+  //  where there might be fake parens levels in-between these levels.
+  // The algorithm will start at the first } on line 4, which is the matching
+  // brace of the initial left brace and at level 2 of the stack. Then,
+  // examining BreakBeforeClosingBrace: false at level 2, it will continue to
+  // the second } on line 4, and will traverse the stack downwards until it
+  // finds the matching { on level 1. Then, examining BreakBeforeClosingBrace:
+  // false at level 1, it will continue to the third } on line 4 and will
+  // traverse the stack downwards until it finds the matching { on level 0.
+  // Then, examining BreakBeforeClosingBrace: true at level 0, the algorithm
+  // will stop and will use the second } on line 4 to determine the length to
+  // return, as in this example the range will include the tokens: {3}}
+  //
+  // The algorithm will only traverse the stack if it encounters braces, array
+  // initializer squares or text proto angle brackets.
   if (!Tok.MatchingParen)
 return 0;
   FormatToken *End = Tok.MatchingParen;
-  while (End->Next && !End->Next->CanBreakBefore) {
-End = End->Next;
+  // Maintains a stack level corresponding to the current End token.
+  int MatchingStackIndex = Stack.size() - 1;
+  // Traverses the stack downwards, looking for the level to which LBrace
+  // corresponds. Returns either a pointer to the matching level or nullptr if
+  // LParen is not found in the initial portion of the stack up to
+  // MatchingStackIndex.
+  auto FindParenState = [&](const FormatToken *LBrace) -> const ParenState * {
+while (MatchingStackIndex >= 0 && Stack[MatchingStackIndex].Tok != LBrace)
+  --MatchingStackIndex;
+return MatchingStackIndex >= 0 ? [MatchingStackIndex] : nullptr;
+  };
+  for (; End->Next; End = End->Next) {
+if (End->Next->CanBreakBefore || !End->Next->closesScope())
+  break;
+if (End->Next->MatchingParen->isOneOf(tok::l_brace,
+  TT_ArrayInitializerLSquare,
+  tok::less)) {
+ 

r331750 - [clang-format] Add raw string formatting to release notes

2018-05-08 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Tue May  8 02:25:12 2018
New Revision: 331750

URL: http://llvm.org/viewvc/llvm-project?rev=331750=rev
Log:
[clang-format] Add raw string formatting to release notes

Reviewers: hans

Reviewed By: hans

Subscribers: cfe-commits

Differential Revision: https://reviews.llvm.org/D46572

Modified:
cfe/trunk/docs/ReleaseNotes.rst

Modified: cfe/trunk/docs/ReleaseNotes.rst
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/docs/ReleaseNotes.rst?rev=331750=331749=331750=diff
==
--- cfe/trunk/docs/ReleaseNotes.rst (original)
+++ cfe/trunk/docs/ReleaseNotes.rst Tue May  8 02:25:12 2018
@@ -216,6 +216,10 @@ AST Matchers
 clang-format
 
 
+- Clang-format will now support detecting and formatting code snippets in raw
+  string literals.  This is configured through the `RawStringFormats` style
+  option.
+
 - ...
 
 libclang


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r330832 - [clang-format] Start formatting cpp code in raw strings in google style

2018-04-25 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Wed Apr 25 07:56:19 2018
New Revision: 330832

URL: http://llvm.org/viewvc/llvm-project?rev=330832=rev
Log:
[clang-format] Start formatting cpp code in raw strings in google style

Summary: This adds some delimiters to detect cpp code in raw strings.

Reviewers: klimek

Reviewed By: klimek

Subscribers: cfe-commits

Differential Revision: https://reviews.llvm.org/D46062

Modified:
cfe/trunk/lib/Format/Format.cpp

Modified: cfe/trunk/lib/Format/Format.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/Format.cpp?rev=330832=330831=330832=diff
==
--- cfe/trunk/lib/Format/Format.cpp (original)
+++ cfe/trunk/lib/Format/Format.cpp Wed Apr 25 07:56:19 2018
@@ -718,20 +718,39 @@ FormatStyle getGoogleStyle(FormatStyle::
   GoogleStyle.ObjCSpaceAfterProperty = false;
   GoogleStyle.ObjCSpaceBeforeProtocolList = true;
   GoogleStyle.PointerAlignment = FormatStyle::PAS_Left;
-  GoogleStyle.RawStringFormats = {{
-  FormatStyle::LK_TextProto,
-  /*Delimiters=*/
+  GoogleStyle.RawStringFormats = {
   {
-  "pb",
-  "PB",
-  "proto",
-  "PROTO",
+  FormatStyle::LK_Cpp,
+  /*Delimiters=*/
+  {
+  "cc",
+  "CC",
+  "cpp",
+  "Cpp",
+  "CPP",
+  "c++",
+  "C++",
+  },
+  /*EnclosingFunctionNames=*/
+  {},
+  /*CanonicalDelimiter=*/"",
+  /*BasedOnStyle=*/"google",
   },
-  /*EnclosingFunctionNames=*/
-  {},
-  /*CanonicalDelimiter=*/"",
-  /*BasedOnStyle=*/"google",
-  }};
+  {
+  FormatStyle::LK_TextProto,
+  /*Delimiters=*/
+  {
+  "pb",
+  "PB",
+  "proto",
+  "PROTO",
+  },
+  /*EnclosingFunctionNames=*/
+  {},
+  /*CanonicalDelimiter=*/"",
+  /*BasedOnStyle=*/"google",
+  },
+  };
   GoogleStyle.SpacesBeforeTrailingComments = 2;
   GoogleStyle.Standard = FormatStyle::LS_Auto;
 


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r330574 - [clang-format] Fix clang-tidy readability problems, NFCI

2018-04-23 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Mon Apr 23 03:02:59 2018
New Revision: 330574

URL: http://llvm.org/viewvc/llvm-project?rev=330574=rev
Log:
[clang-format] Fix clang-tidy readability problems, NFCI

Modified:
cfe/trunk/lib/Format/BreakableToken.h
cfe/trunk/lib/Format/NamespaceEndCommentsFixer.cpp
cfe/trunk/lib/Format/TokenAnnotator.h

Modified: cfe/trunk/lib/Format/BreakableToken.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/BreakableToken.h?rev=330574=330573=330574=diff
==
--- cfe/trunk/lib/Format/BreakableToken.h (original)
+++ cfe/trunk/lib/Format/BreakableToken.h Mon Apr 23 03:02:59 2018
@@ -242,7 +242,7 @@ public:
  encoding::Encoding Encoding, const FormatStyle 
);
 
   Split getSplit(unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit,
- unsigned ReflowColumn,
+ unsigned ContentStartColumn,
  llvm::Regex ) const override;
   void insertBreak(unsigned LineIndex, unsigned TailOffset, Split Split,
WhitespaceManager ) const override;
@@ -284,7 +284,7 @@ public:
   bool supportsReflow() const override { return true; }
   unsigned getLineCount() const override;
   Split getSplit(unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit,
- unsigned ReflowColumn,
+ unsigned ContentStartColumn,
  llvm::Regex ) const override;
   void compressWhitespace(unsigned LineIndex, unsigned TailOffset, Split Split,
   WhitespaceManager ) const override;

Modified: cfe/trunk/lib/Format/NamespaceEndCommentsFixer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/NamespaceEndCommentsFixer.cpp?rev=330574=330573=330574=diff
==
--- cfe/trunk/lib/Format/NamespaceEndCommentsFixer.cpp (original)
+++ cfe/trunk/lib/Format/NamespaceEndCommentsFixer.cpp Mon Apr 23 03:02:59 2018
@@ -110,11 +110,11 @@ void updateEndComment(const FormatToken
 } // namespace
 
 const FormatToken *
-getNamespaceToken(const AnnotatedLine *line,
+getNamespaceToken(const AnnotatedLine *Line,
   const SmallVectorImpl ) {
-  if (!line->Affected || line->InPPDirective || 
!line->startsWith(tok::r_brace))
+  if (!Line->Affected || Line->InPPDirective || 
!Line->startsWith(tok::r_brace))
 return nullptr;
-  size_t StartLineIndex = line->MatchingOpeningBlockLineIndex;
+  size_t StartLineIndex = Line->MatchingOpeningBlockLineIndex;
   if (StartLineIndex == UnwrappedLine::kInvalidIndex)
 return nullptr;
   assert(StartLineIndex < AnnotatedLines.size());

Modified: cfe/trunk/lib/Format/TokenAnnotator.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.h?rev=330574=330573=330574=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.h (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.h Mon Apr 23 03:02:59 2018
@@ -161,7 +161,7 @@ private:
   bool spaceRequiredBetween(const AnnotatedLine , const FormatToken ,
 const FormatToken );
 
-  bool spaceRequiredBefore(const AnnotatedLine , const FormatToken );
+  bool spaceRequiredBefore(const AnnotatedLine , const FormatToken 
);
 
   bool mustBreakBefore(const AnnotatedLine , const FormatToken );
 


___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


r330569 - Revert "[clang-format] Improve Incomplete detection for (text) protos"

2018-04-23 Thread Krasimir Georgiev via cfe-commits
Author: krasimir
Date: Mon Apr 23 01:50:36 2018
New Revision: 330569

URL: http://llvm.org/viewvc/llvm-project?rev=330569=rev
Log:
Revert "[clang-format] Improve Incomplete detection for (text) protos"

This reverts commit r330016.
The incomplete detection has too many false positives, picking up typos
for hard failures and refusing to format anything in that case.

Modified:
cfe/trunk/lib/Format/TokenAnnotator.cpp
cfe/trunk/unittests/Format/FormatTestProto.cpp
cfe/trunk/unittests/Format/FormatTestTextProto.cpp

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=330569=330568=330569=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Mon Apr 23 01:50:36 2018
@@ -592,8 +592,7 @@ private:
   return false;
   }
 }
-// There are no top-level unbalanced braces in text protos.
-return Style.Language != FormatStyle::LK_TextProto;
+return true;
   }
 
   void updateParameterCount(FormatToken *Left, FormatToken *Current) {
@@ -713,11 +712,6 @@ private:
   } else if (Contexts.back().ContextKind == tok::l_paren) {
 Tok->Type = TT_InlineASMColon;
   }
-  // Detects trailing pieces like key:
-  if ((Style.Language == FormatStyle::LK_Proto ||
-   Style.Language == FormatStyle::LK_TextProto) &&
-  !CurrentToken)
-return false;
   break;
 case tok::pipe:
 case tok::amp:
@@ -804,10 +798,6 @@ private:
   if (Previous && Previous->Type != TT_DictLiteral)
 Previous->Type = TT_SelectorName;
 }
-  } else if (Style.Language == FormatStyle::LK_TextProto ||
- Style.Language == FormatStyle::LK_Proto) {
-// In TT_Proto and TT_TextProto, tok::less cannot be a binary operator.
-return false;
   } else {
 Tok->Type = TT_BinaryOperator;
 NonTemplateLess.insert(Tok);
@@ -819,16 +809,13 @@ private:
 case tok::r_square:
   return false;
 case tok::r_brace:
-  // Lines can start with '}' except in text protos.
-  if (Tok->Previous || Style.Language == FormatStyle::LK_TextProto)
+  // Lines can start with '}'.
+  if (Tok->Previous)
 return false;
   break;
 case tok::greater:
-  // In protos and text protos tok::greater cannot be a binary operator.
-  if (Style.Language == FormatStyle::LK_Proto ||
-  Style.Language == FormatStyle::LK_TextProto)
-return false;
-  Tok->Type = TT_BinaryOperator;
+  if (Style.Language != FormatStyle::LK_TextProto)
+Tok->Type = TT_BinaryOperator;
   break;
 case tok::kw_operator:
   if (Style.Language == FormatStyle::LK_TextProto ||

Modified: cfe/trunk/unittests/Format/FormatTestProto.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestProto.cpp?rev=330569=330568=330569=diff
==
--- cfe/trunk/unittests/Format/FormatTestProto.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestProto.cpp Mon Apr 23 01:50:36 2018
@@ -18,21 +18,13 @@ namespace clang {
 namespace format {
 
 class FormatTestProto : public ::testing::Test {
-  enum StatusCheck { SC_ExpectComplete, SC_ExpectIncomplete };
-
 protected:
   static std::string format(llvm::StringRef Code, unsigned Offset,
-unsigned Length, const FormatStyle ,
-StatusCheck CheckComplete = SC_ExpectComplete) {
+unsigned Length, const FormatStyle ) {
 DEBUG(llvm::errs() << "---\n");
 DEBUG(llvm::errs() << Code << "\n\n");
 std::vector Ranges(1, tooling::Range(Offset, Length));
-FormattingAttemptStatus Status;
-tooling::Replacements Replaces =
-reformat(Style, Code, Ranges, "", );
-bool ExpectedCompleteFormat = CheckComplete == SC_ExpectComplete;
-EXPECT_EQ(ExpectedCompleteFormat, Status.FormatComplete)
-<< Code << "\n\n";
+tooling::Replacements Replaces = reformat(Style, Code, Ranges);
 auto Result = applyAllReplacements(Code, Replaces);
 EXPECT_TRUE(static_cast(Result));
 DEBUG(llvm::errs() << "\n" << *Result << "\n\n");
@@ -49,12 +41,6 @@ protected:
 EXPECT_EQ(Code.str(), format(Code)) << "Expected code is not stable";
 EXPECT_EQ(Code.str(), format(test::messUp(Code)));
   }
-
-  static void verifyIncompleteFormat(llvm::StringRef Code) {
-FormatStyle Style = getGoogleStyle(FormatStyle::LK_Proto);
-EXPECT_EQ(Code.str(),
-  format(Code, 0, Code.size(), Style, SC_ExpectIncomplete));
-  }
 };
 
 TEST_F(FormatTestProto, FormatsMessages) {
@@ -506,12 +492,5 @@ TEST_F(FormatTestProto, AcceptsOperatorA
"};");
 }
 
-TEST_F(FormatTestProto, IncompleteFormat) {
-  verifyIncompleteFormat("option (");
-  

  1   2   3   >