[clang] [clang-format] Add SpacesInParensOption for filtering repeated parens (PR #77522)

2024-06-23 Thread Owen Pan via cfe-commits

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


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


[clang] [clang-format] Add SpacesInParensOption for filtering repeated parens (PR #77522)

2024-06-23 Thread Owen Pan via cfe-commits


@@ -17203,6 +17238,23 @@ TEST_F(FormatTest, ConfigurableSpacesInParens) {
   verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces);
   verifyFormat("void __attribute__((naked)) foo(int bar)", Spaces);
   verifyFormat("void f( ) __attribute__((asdf));", Spaces);
+  verifyFormat("x = ( int32 )y;", Spaces);
+  verifyFormat("y = (( int (*)(int) )foo)(x);", Spaces);
+  verifyFormat("decltype(x) y = 42;", Spaces);
+  verifyFormat("decltype((x)) y = z;", Spaces);
+  verifyFormat("decltype((foo( ))) a = foo( );", Spaces);
+  verifyFormat("decltype((bar(10))) a = bar(11);", Spaces);
+  verifyFormat("if ((x - y) && (a ^ b))\n"
+   "  f( );\n",

owenca wrote:

Ditto.

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


[clang] [clang-format] Add SpacesInParensOption for filtering repeated parens (PR #77522)

2024-06-23 Thread Owen Pan via cfe-commits


@@ -17125,6 +17125,23 @@ TEST_F(FormatTest, ConfigurableSpacesInParens) {
   verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces);
   verifyFormat("void __attribute__((naked)) foo(int bar)", Spaces);
   verifyFormat("void f() __attribute__((asdf));", Spaces);
+  verifyFormat("x = (int32)y;", Spaces);
+  verifyFormat("y = ((int (*)(int))foo)(x);", Spaces);
+  verifyFormat("decltype(x) y = 42;", Spaces);
+  verifyFormat("decltype((x)) y = z;", Spaces);
+  verifyFormat("decltype((foo())) a = foo();", Spaces);
+  verifyFormat("decltype((bar(10))) a = bar(11);", Spaces);
+  verifyFormat("if ((x - y) && (a ^ b))\n"
+   "  f();\n",

owenca wrote:

No newline at the end of test cases.

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


[clang] [clang-format] Add SpacesInParensOption for filtering repeated parens (PR #77522)

2024-06-23 Thread Owen Pan via cfe-commits


@@ -17159,6 +17176,23 @@ TEST_F(FormatTest, ConfigurableSpacesInParens) {
   verifyFormat("SomeType *__attribute__( ( attr ) ) *a = NULL;", Spaces);
   verifyFormat("void __attribute__( ( naked ) ) foo( int bar )", Spaces);
   verifyFormat("void f() __attribute__( ( asdf ) );", Spaces);
+  verifyFormat("x = (int32)y;", Spaces);
+  verifyFormat("y = ( (int ( * )( int ))foo )( x );", Spaces);
+  verifyFormat("decltype( x ) y = 42;", Spaces);
+  verifyFormat("decltype( ( x ) ) y = z;", Spaces);
+  verifyFormat("decltype( ( foo() ) ) a = foo();", Spaces);
+  verifyFormat("decltype( ( bar( 10 ) ) ) a = bar( 11 );", Spaces);
+  verifyFormat("if ( ( x - y ) && ( a ^ b ) )\n"
+   "  f();\n",

owenca wrote:

Ditto.

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


[clang] [clang-format] Add SpacesInParensOption for filtering repeated parens (PR #77522)

2024-06-23 Thread Owen Pan via cfe-commits


@@ -17310,6 +17362,63 @@ TEST_F(FormatTest, ConfigurableSpacesInParens) {
   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
   verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
+
+  // Check ExceptDoubleParentheses spaces
+  Spaces.IndentWidth = 2;
+  Spaces.SpacesInParens = FormatStyle::SIPO_Custom;
+  Spaces.SpacesInParensOptions = {};
+  Spaces.SpacesInParensOptions.Other = true;
+  Spaces.SpacesInParensOptions.ExceptDoubleParentheses = true;
+  verifyFormat("SomeType *__attribute__(( attr )) *a = NULL;", Spaces);
+  verifyFormat("void __attribute__(( naked )) foo( int bar )", Spaces);
+  verifyFormat("void f() __attribute__(( asdf ));", Spaces);
+  verifyFormat("__attribute__(( __aligned__( x ) )) z;", Spaces);
+  verifyFormat("int x __attribute__(( aligned( 16 ) )) = 0;", Spaces);
+  verifyFormat("class __declspec( dllimport ) X {};", Spaces);
+  verifyFormat("class __declspec(( dllimport )) X {};", Spaces);
+  verifyFormat("int x = ( ( a - 1 ) * 3 );", Spaces);
+  verifyFormat("int x = ( 3 * ( a - 1 ) );", Spaces);
+  verifyFormat("decltype( x ) y = 42;", Spaces);
+  verifyFormat("decltype(( bar( 10 ) )) a = bar( 11 );", Spaces);
+  verifyFormat("if (( i = j ))\n"
+   "  do_something( i );",
+   Spaces);
+
+  Spaces.SpacesInParens = FormatStyle::SIPO_Custom;
+  Spaces.SpacesInParensOptions = {};
+  Spaces.SpacesInParensOptions.InConditionalStatements = true;
+  Spaces.SpacesInParensOptions.ExceptDoubleParentheses = true;
+  verifyFormat("while ( (bool)1 )\n"
+   "  continue;",
+   Spaces);
+  verifyFormat("while ((i = j))\n"
+   "  continue;",
+   Spaces);
+  verifyFormat("do {\n"
+   "  do_something((int)i);\n"
+   "} while ( something() );",
+   Spaces);
+  verifyFormat("do {\n"
+   "  do_something((int)i);\n"
+   "} while ((i = i + 1));",
+   Spaces);
+  verifyFormat("if ( (x - y) && (a ^ b) )\n"
+   "  f();\n",

owenca wrote:

Ditto.

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


[clang] [clang-format] Add SpacesInParensOption for filtering repeated parens (PR #77522)

2024-06-23 Thread Owen Pan via cfe-commits

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


[clang] [clang-format] Don't count template template parameter as declaration (PR #96396)

2024-06-22 Thread Owen Pan via cfe-commits

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


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


[clang] [clang-format] Don't count template template parameter as declaration (PR #95025)

2024-06-22 Thread Owen Pan via cfe-commits

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


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


[clang] [clang-format] Annotate r_paren before braced list as TT_CastRParen (PR #96271)

2024-06-21 Thread Owen Pan via cfe-commits

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


[clang] [clang-format][NFC] Add CMake target clang-format-check-format (PR #95873)

2024-06-21 Thread Owen Pan via cfe-commits

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


[clang] [clang-format] Annotate r_paren before braced list as TT_CastRParen (PR #96271)

2024-06-20 Thread Owen Pan via cfe-commits

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


[clang] [clang-format] Annotate r_paren before braced list as TT_CastRParen (PR #96271)

2024-06-20 Thread Owen Pan via cfe-commits

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


[clang] [clang-format] Annotate r_paren before braced list as TT_CastRParen (PR #96271)

2024-06-20 Thread Owen Pan via cfe-commits

https://github.com/owenca created 
https://github.com/llvm/llvm-project/pull/96271

None

>From 44eec3e8d4bec1de03428d42dce98a998f282825 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Thu, 20 Jun 2024 19:38:38 -0700
Subject: [PATCH] [clang-format] Annotate r_paren before braced list as
 TT_CastRParen

---
 clang/lib/Format/TokenAnnotator.cpp   | 5 +
 clang/unittests/Format/TokenAnnotatorTest.cpp | 4 
 2 files changed, 9 insertions(+)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 63a028a6f4779..55c5ecee45e0c 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2837,6 +2837,11 @@ class AnnotatingParser {
 if (!AfterRParen->Next)
   return false;
 
+if (AfterRParen->is(tok::l_brace) &&
+AfterRParen->getBlockKind() == BK_BracedInit) {
+  return true;
+}
+
 // If the next token after the parenthesis is a unary operator, assume
 // that this is cast, unless there are unexpected tokens inside the
 // parenthesis.
diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 0dc506458f7c3..12c4b7fdd5ac2 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -662,6 +662,10 @@ TEST_F(TokenAnnotatorTest, UnderstandsCasts) {
   EXPECT_TOKEN(Tokens[3], tok::r_paren, TT_Unknown);
   EXPECT_TOKEN(Tokens[4], tok::amp, TT_BinaryOperator);
 
+  Tokens = annotate("return (struct foo){};");
+  ASSERT_EQ(Tokens.size(), 9u) << Tokens;
+  EXPECT_TOKEN(Tokens[4], tok::r_paren, TT_CastRParen);
+
   Tokens = annotate("#define FOO(bar) foo((uint64_t))");
   ASSERT_EQ(Tokens.size(), 15u) << Tokens;
   EXPECT_TOKEN(Tokens[10], tok::r_paren, TT_CastRParen);

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


[clang] [clang-format[NFC] Clean up AnnotatingParser::rParenEndsCast() (PR #96128)

2024-06-20 Thread Owen Pan via cfe-commits

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


[clang] [clang-format[NFC] Clean up AnnotatingParser::rParenEndsCast() (PR #96128)

2024-06-20 Thread Owen Pan via cfe-commits

https://github.com/owenca updated 
https://github.com/llvm/llvm-project/pull/96128

>From 420cde9e46d8eb3f3043d18cf78fbaef0f89ccbb Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Wed, 19 Jun 2024 18:07:56 -0700
Subject: [PATCH] [clang-format[NFC] Clean up
 AnnotatingParser::rParenEndsCast()

---
 clang/lib/Format/TokenAnnotator.cpp | 83 -
 1 file changed, 46 insertions(+), 37 deletions(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 87e3e712d6993..63a028a6f4779 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2661,18 +2661,27 @@ class AnnotatingParser {
 
   /// Determine whether ')' is ending a cast.
   bool rParenEndsCast(const FormatToken ) {
+assert(Tok.is(tok::r_paren));
+
+if (!Tok.MatchingParen || !Tok.Previous)
+  return false;
+
 // C-style casts are only used in C++, C# and Java.
-if (!Style.isCSharp() && !IsCpp && Style.Language != FormatStyle::LK_Java)
+if (!IsCpp && !Style.isCSharp() && Style.Language != FormatStyle::LK_Java)
   return false;
 
+const auto *LParen = Tok.MatchingParen;
+const auto *BeforeRParen = Tok.Previous;
+const auto *AfterRParen = Tok.Next;
+
 // Empty parens aren't casts and there are no casts at the end of the line.
-if (Tok.Previous == Tok.MatchingParen || !Tok.Next || !Tok.MatchingParen)
+if (BeforeRParen == LParen || !AfterRParen)
   return false;
 
-if (Tok.MatchingParen->is(TT_OverloadedOperatorLParen))
+if (LParen->is(TT_OverloadedOperatorLParen))
   return false;
 
-FormatToken *LeftOfParens = Tok.MatchingParen->getPreviousNonComment();
+auto *LeftOfParens = LParen->getPreviousNonComment();
 if (LeftOfParens) {
   // If there is a closing parenthesis left of the current
   // parentheses, look past it as these might be chained casts.
@@ -2728,37 +2737,38 @@ class AnnotatingParser {
   }
 }
 
-if (Tok.Next->is(tok::question) ||
-(Tok.Next->is(tok::ampamp) && !Tok.Previous->isTypeName(LangOpts))) {
+if (AfterRParen->is(tok::question) ||
+(AfterRParen->is(tok::ampamp) && !BeforeRParen->isTypeName(LangOpts))) 
{
   return false;
 }
 
 // `foreach((A a, B b) in someList)` should not be seen as a cast.
-if (Tok.Next->is(Keywords.kw_in) && Style.isCSharp())
+if (AfterRParen->is(Keywords.kw_in) && Style.isCSharp())
   return false;
 
 // 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_requires, tok::kw_throw, tok::arrow,
-  Keywords.kw_override, Keywords.kw_final) ||
-isCppAttribute(IsCpp, *Tok.Next)) {
+if (AfterRParen->isOneOf(tok::kw_noexcept, tok::kw_volatile, tok::kw_const,
+ tok::kw_requires, tok::kw_throw, tok::arrow,
+ Keywords.kw_override, Keywords.kw_final) ||
+isCppAttribute(IsCpp, *AfterRParen)) {
   return false;
 }
 
 // As Java has no function types, a "(" after the ")" likely means that 
this
 // is a cast.
-if (Style.Language == FormatStyle::LK_Java && Tok.Next->is(tok::l_paren))
+if (Style.Language == FormatStyle::LK_Java && 
AfterRParen->is(tok::l_paren))
   return true;
 
 // If a (non-string) literal follows, this is likely a cast.
-if (Tok.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof) ||
-(Tok.Next->Tok.isLiteral() && Tok.Next->isNot(tok::string_literal))) {
+if (AfterRParen->isOneOf(tok::kw_sizeof, tok::kw_alignof) ||
+(AfterRParen->Tok.isLiteral() &&
+ AfterRParen->isNot(tok::string_literal))) {
   return true;
 }
 
 // Heuristically try to determine whether the parentheses contain a type.
-auto IsQualifiedPointerOrReference = [](FormatToken *T,
+auto IsQualifiedPointerOrReference = [](const FormatToken *T,
 const LangOptions ) {
   // This is used to handle cases such as x = (foo *const)
   assert(!T->isTypeName(LangOpts) && "Should have already been checked");
@@ -2791,12 +2801,11 @@ class AnnotatingParser {
   return T && T->is(TT_PointerOrReference);
 };
 bool ParensAreType =
-!Tok.Previous ||
-Tok.Previous->isOneOf(TT_TemplateCloser, TT_TypeDeclarationParen) ||
-Tok.Previous->isTypeName(LangOpts) ||
-IsQualifiedPointerOrReference(Tok.Previous, LangOpts);
+BeforeRParen->isOneOf(TT_TemplateCloser, TT_TypeDeclarationParen) ||
+BeforeRParen->isTypeName(LangOpts) ||
+IsQualifiedPointerOrReference(BeforeRParen, LangOpts);
 bool ParensCouldEndDecl =
-Tok.Next->isOneOf(tok::equal, tok::semi, tok::l_brace, tok::greater);
+AfterRParen->isOneOf(tok::equal, tok::semi, tok::l_brace, 
tok::greater);
 if 

[clang] [clang-format[NFC] Clean up AnnotatingParser::rParenEndsCast() (PR #96128)

2024-06-19 Thread Owen Pan via cfe-commits

https://github.com/owenca created 
https://github.com/llvm/llvm-project/pull/96128

None

>From 04618d27f9ebd045dfae5bfc341056c483fab0d1 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Wed, 19 Jun 2024 18:07:56 -0700
Subject: [PATCH] [clang-format[NFC] Clean up
 AnnotatingParser::rParenEndsCast()

---
 clang/lib/Format/TokenAnnotator.cpp | 81 -
 1 file changed, 46 insertions(+), 35 deletions(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 87e3e712d6993..67c8f7f5c8bdd 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2661,18 +2661,27 @@ class AnnotatingParser {
 
   /// Determine whether ')' is ending a cast.
   bool rParenEndsCast(const FormatToken ) {
+assert(Tok.is(tok::r_paren));
+
+if (!Tok.Previous || !Tok.MatchingParen)
+  return false;
+
 // C-style casts are only used in C++, C# and Java.
-if (!Style.isCSharp() && !IsCpp && Style.Language != FormatStyle::LK_Java)
+if (!IsCpp && !Style.isCSharp() && Style.Language != FormatStyle::LK_Java)
   return false;
 
+const auto *LParen = Tok.MatchingParen;
+const auto *BeforeRParen = Tok.Previous;
+const auto *AfterRParen = Tok.Next;
+
 // Empty parens aren't casts and there are no casts at the end of the line.
-if (Tok.Previous == Tok.MatchingParen || !Tok.Next || !Tok.MatchingParen)
+if (BeforeRParen == LParen || !AfterRParen)
   return false;
 
-if (Tok.MatchingParen->is(TT_OverloadedOperatorLParen))
+if (LParen->is(TT_OverloadedOperatorLParen))
   return false;
 
-FormatToken *LeftOfParens = Tok.MatchingParen->getPreviousNonComment();
+FormatToken *LeftOfParens = LParen->getPreviousNonComment();
 if (LeftOfParens) {
   // If there is a closing parenthesis left of the current
   // parentheses, look past it as these might be chained casts.
@@ -2728,37 +2737,38 @@ class AnnotatingParser {
   }
 }
 
-if (Tok.Next->is(tok::question) ||
-(Tok.Next->is(tok::ampamp) && !Tok.Previous->isTypeName(LangOpts))) {
+if (AfterRParen->is(tok::question) ||
+(AfterRParen->is(tok::ampamp) && !BeforeRParen->isTypeName(LangOpts))) 
{
   return false;
 }
 
 // `foreach((A a, B b) in someList)` should not be seen as a cast.
-if (Tok.Next->is(Keywords.kw_in) && Style.isCSharp())
+if (AfterRParen->is(Keywords.kw_in) && Style.isCSharp())
   return false;
 
 // 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_requires, tok::kw_throw, tok::arrow,
-  Keywords.kw_override, Keywords.kw_final) ||
-isCppAttribute(IsCpp, *Tok.Next)) {
+if (AfterRParen->isOneOf(tok::kw_noexcept, tok::kw_volatile, tok::kw_const,
+ tok::kw_requires, tok::kw_throw, tok::arrow,
+ Keywords.kw_override, Keywords.kw_final) ||
+isCppAttribute(IsCpp, *AfterRParen)) {
   return false;
 }
 
 // As Java has no function types, a "(" after the ")" likely means that 
this
 // is a cast.
-if (Style.Language == FormatStyle::LK_Java && Tok.Next->is(tok::l_paren))
+if (Style.Language == FormatStyle::LK_Java && 
AfterRParen->is(tok::l_paren))
   return true;
 
 // If a (non-string) literal follows, this is likely a cast.
-if (Tok.Next->isOneOf(tok::kw_sizeof, tok::kw_alignof) ||
-(Tok.Next->Tok.isLiteral() && Tok.Next->isNot(tok::string_literal))) {
+if (AfterRParen->isOneOf(tok::kw_sizeof, tok::kw_alignof) ||
+(AfterRParen->Tok.isLiteral() &&
+ AfterRParen->isNot(tok::string_literal))) {
   return true;
 }
 
 // Heuristically try to determine whether the parentheses contain a type.
-auto IsQualifiedPointerOrReference = [](FormatToken *T,
+auto IsQualifiedPointerOrReference = [](const FormatToken *T,
 const LangOptions ) {
   // This is used to handle cases such as x = (foo *const)
   assert(!T->isTypeName(LangOpts) && "Should have already been checked");
@@ -2791,12 +2801,11 @@ class AnnotatingParser {
   return T && T->is(TT_PointerOrReference);
 };
 bool ParensAreType =
-!Tok.Previous ||
-Tok.Previous->isOneOf(TT_TemplateCloser, TT_TypeDeclarationParen) ||
-Tok.Previous->isTypeName(LangOpts) ||
-IsQualifiedPointerOrReference(Tok.Previous, LangOpts);
+BeforeRParen->isOneOf(TT_TemplateCloser, TT_TypeDeclarationParen) ||
+BeforeRParen->isTypeName(LangOpts) ||
+IsQualifiedPointerOrReference(BeforeRParen, LangOpts);
 bool ParensCouldEndDecl =
-Tok.Next->isOneOf(tok::equal, tok::semi, tok::l_brace, tok::greater);
+AfterRParen->isOneOf(tok::equal, tok::semi, tok::l_brace, 
tok::greater);

[clang] [clang-format] Correctly annotate l_brace after TypenameMacro (PR #96026)

2024-06-19 Thread Owen Pan via cfe-commits

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


[clang] [clang-format] Correctly annotate l_brace after TypenameMacro (PR #96026)

2024-06-19 Thread Owen Pan via cfe-commits


@@ -3180,6 +3180,18 @@ TEST_F(TokenAnnotatorTest, FunctionTryBlock) {
   EXPECT_TOKEN(Tokens[36], tok::l_brace, TT_FunctionLBrace);
 }
 
+TEST_F(TokenAnnotatorTest, TypenameMacro) {
+  auto Style = getLLVMStyle();
+  Style.TypenameMacros.push_back("STRUCT");
+
+  auto Tokens = annotate("STRUCT(T, B) { int i; };", Style);
+  ASSERT_EQ(Tokens.size(), 13u);
+  EXPECT_TOKEN(Tokens[0], tok::identifier, TT_TypenameMacro);
+  EXPECT_TOKEN(Tokens[1], tok::l_paren, TT_TypeDeclarationParen);
+  EXPECT_TOKEN(Tokens[5], tok::r_paren, TT_TypeDeclarationParen);
+  EXPECT_TOKEN(Tokens[6], tok::l_brace, TT_Unknown);

owenca wrote:

> Is `TT_Unknown` the correct type?

Yes. We use it to verify that a token is not annotated (incorrectly).

> I know we can't really say if it's a `TT_StructLBrace` or `TT_ClassLBrace` 
> (or even `TT_UnionLBrace`), but would it harm to just guess one of them?

Or `TT_EnumLBrace` or anyone in 
[here](https://github.com/llvm/llvm-project/pull/93634#issuecomment-2156968344).
 We shouldn’t make a wild guess because the type of the braces depends on how 
the macro is defined (and on what’s between the braces).

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


[clang] [clang-format] Correctly annotate l_brace after TypenameMacro (PR #96026)

2024-06-18 Thread Owen Pan via cfe-commits

https://github.com/owenca created 
https://github.com/llvm/llvm-project/pull/96026

Closes #95418.

>From cc4cd4d9e7eea3ba670a29a053d18739b40058ab Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Tue, 18 Jun 2024 22:29:53 -0700
Subject: [PATCH] [clang-format] Correctly annotate l_brace after TypenameMacro

Closes #95418.
---
 clang/lib/Format/UnwrappedLineParser.cpp  | 12 +---
 clang/unittests/Format/FormatTest.cpp |  3 +++
 clang/unittests/Format/TokenAnnotatorTest.cpp | 12 
 3 files changed, 24 insertions(+), 3 deletions(-)

diff --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index ce877ac2bb9ef..d406a531a5c0c 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -1910,7 +1910,8 @@ void UnwrappedLineParser::parseStructuralElement(
 } else if (Style.BraceWrapping.AfterFunction) {
   addUnwrappedLine();
 }
-FormatTok->setFinalizedType(TT_FunctionLBrace);
+if (!Previous || Previous->isNot(TT_TypeDeclarationParen))
+  FormatTok->setFinalizedType(TT_FunctionLBrace);
 parseBlock();
 IsDecltypeAutoFunction = false;
 addUnwrappedLine();
@@ -2545,10 +2546,10 @@ bool UnwrappedLineParser::parseParens(TokenType 
AmpAmpTokenType) {
   if (Style.Language == FormatStyle::LK_Java && 
FormatTok->is(tok::l_brace))
 parseChildBlock();
   break;
-case tok::r_paren:
+case tok::r_paren: {
+  const auto *Prev = LeftParen->Previous;
   if (!MightBeStmtExpr && !MightBeFoldExpr && !Line->InMacroBody &&
   Style.RemoveParentheses > FormatStyle::RPS_Leave) {
-const auto *Prev = LeftParen->Previous;
 const auto *Next = Tokens->peekNextToken();
 const bool DoubleParens =
 Prev && Prev->is(tok::l_paren) && Next && Next->is(tok::r_paren);
@@ -2570,8 +2571,13 @@ bool UnwrappedLineParser::parseParens(TokenType 
AmpAmpTokenType) {
   FormatTok->Optional = true;
 }
   }
+  if (Prev && Prev->is(TT_TypenameMacro)) {
+LeftParen->setFinalizedType(TT_TypeDeclarationParen);
+FormatTok->setFinalizedType(TT_TypeDeclarationParen);
+  }
   nextToken();
   return SeenEqual;
+}
 case tok::r_brace:
   // A "}" inside parenthesis is an error if there wasn't a matching "{".
   return SeenEqual;
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index fc63afce70042..db1decb20d626 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -27007,6 +27007,9 @@ TEST_F(FormatTest, RemoveSemicolon) {
"; int bar;",
Style);
 #endif
+
+  Style.TypenameMacros.push_back("STRUCT");
+  verifyFormat("STRUCT(T, B) { int i; };", Style);
 }
 
 TEST_F(FormatTest, BreakAfterAttributes) {
diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 3735316dc3478..0dc506458f7c3 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -3180,6 +3180,18 @@ TEST_F(TokenAnnotatorTest, FunctionTryBlock) {
   EXPECT_TOKEN(Tokens[36], tok::l_brace, TT_FunctionLBrace);
 }
 
+TEST_F(TokenAnnotatorTest, TypenameMacro) {
+  auto Style = getLLVMStyle();
+  Style.TypenameMacros.push_back("STRUCT");
+
+  auto Tokens = annotate("STRUCT(T, B) { int i; };", Style);
+  ASSERT_EQ(Tokens.size(), 13u);
+  EXPECT_TOKEN(Tokens[0], tok::identifier, TT_TypenameMacro);
+  EXPECT_TOKEN(Tokens[1], tok::l_paren, TT_TypeDeclarationParen);
+  EXPECT_TOKEN(Tokens[5], tok::r_paren, TT_TypeDeclarationParen);
+  EXPECT_TOKEN(Tokens[6], tok::l_brace, TT_Unknown);
+}
+
 } // namespace
 } // namespace format
 } // namespace clang

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


[clang] [clang-format] Handle function try block with ctor-initializer (PR #95878)

2024-06-18 Thread Owen Pan via cfe-commits

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


[clang] [clang-format] Handle function try block with ctor-initializer (PR #95878)

2024-06-18 Thread Owen Pan via cfe-commits

https://github.com/owenca updated 
https://github.com/llvm/llvm-project/pull/95878

>From 299924c9f9485e7a784ffedcb6ec4fbccf5ad6f7 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Mon, 17 Jun 2024 21:13:10 -0700
Subject: [PATCH 1/2] [clang-format] Handle function try block with
 ctor-initializer

Fixes #58987.
Fixes #95679.
---
 clang/lib/Format/UnwrappedLineParser.cpp  | 17 +++--
 clang/unittests/Format/TokenAnnotatorTest.cpp | 15 +++
 2 files changed, 26 insertions(+), 6 deletions(-)

diff --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index df5bb757a99ec..ce877ac2bb9ef 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -2955,9 +2955,15 @@ void UnwrappedLineParser::parseTryCatch() {
   assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) && "'try' expected");
   nextToken();
   bool NeedsUnwrappedLine = false;
+  bool HasCtorInitializer = false;
   if (FormatTok->is(tok::colon)) {
+auto *Colon = FormatTok;
 // We are in a function try block, what comes is an initializer list.
 nextToken();
+if (FormatTok->is(tok::identifier)) {
+  HasCtorInitializer = true;
+  Colon->setFinalizedType(TT_CtorInitializerColon);
+}
 
 // In case identifiers were removed by clang-tidy, what might follow is
 // multiple commas in sequence - before the first identifier.
@@ -2966,14 +2972,11 @@ void UnwrappedLineParser::parseTryCatch() {
 
 while (FormatTok->is(tok::identifier)) {
   nextToken();
-  if (FormatTok->is(tok::l_paren))
+  if (FormatTok->is(tok::l_paren)) {
 parseParens();
-  if (FormatTok->Previous && FormatTok->Previous->is(tok::identifier) &&
-  FormatTok->is(tok::l_brace)) {
-do {
-  nextToken();
-} while (FormatTok->isNot(tok::r_brace));
+  } else if (FormatTok->is(tok::l_brace)) {
 nextToken();
+parseBracedList();
   }
 
   // In case identifiers were removed by clang-tidy, what might follow is
@@ -2989,6 +2992,8 @@ void UnwrappedLineParser::parseTryCatch() {
   keepAncestorBraces();
 
   if (FormatTok->is(tok::l_brace)) {
+if (HasCtorInitializer)
+  FormatTok->setFinalizedType(TT_FunctionLBrace);
 CompoundStatementIndenter Indenter(this, Style, Line->Level);
 parseBlock();
 if (Style.BraceWrapping.BeforeCatch)
diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 3e9638d9f3c56..487582ee4e10d 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -3164,6 +3164,21 @@ TEST_F(TokenAnnotatorTest, CppAltOperatorKeywords) {
   EXPECT_TOKEN(Tokens[1], tok::identifier, TT_StartOfName);
 }
 
+TEST_F(TokenAnnotatorTest, FunctionTryBlock) {
+  auto Tokens =
+  annotate("Ctor::Ctor(int x, int y) try\n"
+   ": foo{[]() -> std::string { return {}; }(), x}, bar{y} {\n"
+   "} catch (...) {\n"
+   "}");
+  ASSERT_EQ(Tokens.size(), 47u);
+  EXPECT_TOKEN(Tokens[11], tok::colon, TT_CtorInitializerColon);
+  EXPECT_TOKEN(Tokens[14], tok::l_square, TT_LambdaLSquare);
+  EXPECT_TOKEN(Tokens[18], tok::arrow, TT_TrailingReturnArrow);
+  EXPECT_TOKEN(Tokens[22], tok::l_brace, TT_LambdaLBrace);
+  EXPECT_TOKEN(Tokens[33], tok::comma, TT_CtorInitializerComma);
+  EXPECT_TOKEN(Tokens[38], tok::l_brace, TT_FunctionLBrace);
+}
+
 } // namespace
 } // namespace format
 } // namespace clang

>From 733592d7cebd0b54ad9b08b506ab971f4549d7f0 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Tue, 18 Jun 2024 17:53:51 -0700
Subject: [PATCH 2/2] Tweak the test case.

---
 clang/unittests/Format/TokenAnnotatorTest.cpp | 15 ---
 1 file changed, 8 insertions(+), 7 deletions(-)

diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 487582ee4e10d..3735316dc3478 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -3166,17 +3166,18 @@ TEST_F(TokenAnnotatorTest, CppAltOperatorKeywords) {
 
 TEST_F(TokenAnnotatorTest, FunctionTryBlock) {
   auto Tokens =
-  annotate("Ctor::Ctor(int x, int y) try\n"
-   ": foo{[]() -> std::string { return {}; }(), x}, bar{y} {\n"
+  annotate("Foo::Foo(int x, int y) try\n"
+   ": foo{[] -> std::string { return {}; }(), x}, bar{y} {\n"
"} catch (...) {\n"
"}");
-  ASSERT_EQ(Tokens.size(), 47u);
+  ASSERT_EQ(Tokens.size(), 45u);
+  EXPECT_TOKEN(Tokens[2], tok::identifier, TT_CtorDtorDeclName);
   EXPECT_TOKEN(Tokens[11], tok::colon, TT_CtorInitializerColon);
   EXPECT_TOKEN(Tokens[14], tok::l_square, TT_LambdaLSquare);
-  EXPECT_TOKEN(Tokens[18], tok::arrow, TT_TrailingReturnArrow);
-  EXPECT_TOKEN(Tokens[22], tok::l_brace, TT_LambdaLBrace);
-  EXPECT_TOKEN(Tokens[33], tok::comma, 

[clang] [clang-format] Add option to remove leading blank lines (PR #91221)

2024-06-18 Thread Owen Pan via cfe-commits


@@ -45,6 +45,9 @@ TEST_F(FormatTest, FormatsGlobalStatementsAt0) {
   verifyFormat("\nint i;", " \n\t \v \f  int i;");
   verifyFormat("int i;\nint j;", "int i; int j;");
   verifyFormat("int i;\nint j;", "int i;\n  int j;");
+  auto Style = getLLVMStyle();

owenca wrote:

An empty line before `auto Style = ...`?

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


[clang] [clang-format] Add option to remove leading blank lines (PR #91221)

2024-06-18 Thread Owen Pan via cfe-commits


@@ -21947,6 +21950,10 @@ TEST_F(FormatTest, HandlesUTF8BOM) {
   verifyFormat("\xef\xbb\xbf");
   verifyFormat("\xef\xbb\xbf#include ");
   verifyFormat("\xef\xbb\xbf\n#include ");
+  auto Style = getLLVMStyle();

owenca wrote:

Ditto.

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


[clang] [clang-format] Add option to remove leading blank lines (PR #91221)

2024-06-18 Thread Owen Pan via cfe-commits

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


[clang] [clang-format] Add option to remove leading blank lines (PR #91221)

2024-06-18 Thread Owen Pan via cfe-commits

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


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


[clang] [clang-format] Handle function try block with ctor-initializer (PR #95878)

2024-06-17 Thread Owen Pan via cfe-commits

https://github.com/owenca created 
https://github.com/llvm/llvm-project/pull/95878

Fixes #58987.
Fixes #95679.

>From 299924c9f9485e7a784ffedcb6ec4fbccf5ad6f7 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Mon, 17 Jun 2024 21:13:10 -0700
Subject: [PATCH] [clang-format] Handle function try block with
 ctor-initializer

Fixes #58987.
Fixes #95679.
---
 clang/lib/Format/UnwrappedLineParser.cpp  | 17 +++--
 clang/unittests/Format/TokenAnnotatorTest.cpp | 15 +++
 2 files changed, 26 insertions(+), 6 deletions(-)

diff --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index df5bb757a99ec..ce877ac2bb9ef 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -2955,9 +2955,15 @@ void UnwrappedLineParser::parseTryCatch() {
   assert(FormatTok->isOneOf(tok::kw_try, tok::kw___try) && "'try' expected");
   nextToken();
   bool NeedsUnwrappedLine = false;
+  bool HasCtorInitializer = false;
   if (FormatTok->is(tok::colon)) {
+auto *Colon = FormatTok;
 // We are in a function try block, what comes is an initializer list.
 nextToken();
+if (FormatTok->is(tok::identifier)) {
+  HasCtorInitializer = true;
+  Colon->setFinalizedType(TT_CtorInitializerColon);
+}
 
 // In case identifiers were removed by clang-tidy, what might follow is
 // multiple commas in sequence - before the first identifier.
@@ -2966,14 +2972,11 @@ void UnwrappedLineParser::parseTryCatch() {
 
 while (FormatTok->is(tok::identifier)) {
   nextToken();
-  if (FormatTok->is(tok::l_paren))
+  if (FormatTok->is(tok::l_paren)) {
 parseParens();
-  if (FormatTok->Previous && FormatTok->Previous->is(tok::identifier) &&
-  FormatTok->is(tok::l_brace)) {
-do {
-  nextToken();
-} while (FormatTok->isNot(tok::r_brace));
+  } else if (FormatTok->is(tok::l_brace)) {
 nextToken();
+parseBracedList();
   }
 
   // In case identifiers were removed by clang-tidy, what might follow is
@@ -2989,6 +2992,8 @@ void UnwrappedLineParser::parseTryCatch() {
   keepAncestorBraces();
 
   if (FormatTok->is(tok::l_brace)) {
+if (HasCtorInitializer)
+  FormatTok->setFinalizedType(TT_FunctionLBrace);
 CompoundStatementIndenter Indenter(this, Style, Line->Level);
 parseBlock();
 if (Style.BraceWrapping.BeforeCatch)
diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 3e9638d9f3c56..487582ee4e10d 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -3164,6 +3164,21 @@ TEST_F(TokenAnnotatorTest, CppAltOperatorKeywords) {
   EXPECT_TOKEN(Tokens[1], tok::identifier, TT_StartOfName);
 }
 
+TEST_F(TokenAnnotatorTest, FunctionTryBlock) {
+  auto Tokens =
+  annotate("Ctor::Ctor(int x, int y) try\n"
+   ": foo{[]() -> std::string { return {}; }(), x}, bar{y} {\n"
+   "} catch (...) {\n"
+   "}");
+  ASSERT_EQ(Tokens.size(), 47u);
+  EXPECT_TOKEN(Tokens[11], tok::colon, TT_CtorInitializerColon);
+  EXPECT_TOKEN(Tokens[14], tok::l_square, TT_LambdaLSquare);
+  EXPECT_TOKEN(Tokens[18], tok::arrow, TT_TrailingReturnArrow);
+  EXPECT_TOKEN(Tokens[22], tok::l_brace, TT_LambdaLBrace);
+  EXPECT_TOKEN(Tokens[33], tok::comma, TT_CtorInitializerComma);
+  EXPECT_TOKEN(Tokens[38], tok::l_brace, TT_FunctionLBrace);
+}
+
 } // namespace
 } // namespace format
 } // namespace clang

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


[clang] [clang-format][NFC] Add CMake target clang-format-check-format (PR #95873)

2024-06-17 Thread Owen Pan via cfe-commits

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


[clang] [clang-format][NFC] Add CMake target clang-format-check-format (PR #95873)

2024-06-17 Thread Owen Pan via cfe-commits

https://github.com/owenca created 
https://github.com/llvm/llvm-project/pull/95873

Adpated from polly-check-format.

>From ab2a61d1939f4be4551949e979fd43b9e11c5c49 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Mon, 17 Jun 2024 18:49:22 -0700
Subject: [PATCH] [clang-format][NFC] Add CMake target
 clang-format-check-format

Adpated from polly-check-format.
---
 clang/lib/Format/CMakeLists.txt | 24 
 1 file changed, 24 insertions(+)

diff --git a/clang/lib/Format/CMakeLists.txt b/clang/lib/Format/CMakeLists.txt
index 84a3c136f650a..b787b11ac7b74 100644
--- a/clang/lib/Format/CMakeLists.txt
+++ b/clang/lib/Format/CMakeLists.txt
@@ -29,3 +29,27 @@ add_clang_library(clangFormat
   clangToolingCore
   clangToolingInclusions
   )
+
+file(GLOB_RECURSE files
+  *.cpp
+  *.h
+  ../../include/clang/Format/*.h
+  ../../tools/clang-format/*.cpp
+  ../../unittests/Format/*.cpp
+  ../../unittests/Format/*.h
+  )
+
+set(check_format_depends)
+set(i 0)
+foreach (file IN LISTS files)
+  add_custom_command(OUTPUT clang-format-check-format${i}
+COMMAND clang-format ${file} | diff -u ${file} -
+VERBATIM
+COMMENT "Checking format of ${file}..."
+  )
+  list(APPEND check_format_depends "clang-format-check-format${i}")
+
+  math(EXPR i ${i}+1)
+endforeach ()
+
+add_custom_target(clang-format-check-format DEPENDS ${check_format_depends})

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


[clang] [clang-format][NFC] Add FormatToken::isAccessSpecifierKeyword() (PR #95727)

2024-06-17 Thread Owen Pan via cfe-commits

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


[clang] [clang-format][NFC] Add FormatToken::isAccessSpecifierKeyword() (PR #95727)

2024-06-16 Thread Owen Pan via cfe-commits

https://github.com/owenca created 
https://github.com/llvm/llvm-project/pull/95727

None

>From ec9b902518ef09d77e8b32777032a852d33476fd Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Sun, 16 Jun 2024 17:47:56 -0700
Subject: [PATCH] [clang-format][NFC] Add
 FormatToken::isAccessSpecifierKeyword()

---
 clang/lib/Format/FormatToken.h   | 20 ++-
 clang/lib/Format/TokenAnnotator.cpp  | 44 +++-
 clang/lib/Format/UnwrappedLineParser.cpp | 23 ++---
 3 files changed, 43 insertions(+), 44 deletions(-)

diff --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index e4a4f27e502b1..4ffd745bf9307 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -667,12 +667,16 @@ struct FormatToken {
 return Tok.isObjCAtKeyword(Kind);
   }
 
+  bool isAccessSpecifierKeyword() const {
+return isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private);
+  }
+
   bool isAccessSpecifier(bool ColonRequired = true) const {
-if (!isOneOf(tok::kw_public, tok::kw_protected, tok::kw_private))
+if (!isAccessSpecifierKeyword())
   return false;
 if (!ColonRequired)
   return true;
-const auto NextNonComment = getNextNonComment();
+const auto *NextNonComment = getNextNonComment();
 return NextNonComment && NextNonComment->is(tok::colon);
   }
 
@@ -1656,10 +1660,12 @@ struct AdditionalKeywords {
   /// If \c AcceptIdentifierName is true, returns true not only for keywords,
   // but also for IdentifierName tokens (aka pseudo-keywords), such as
   // ``yield``.
-  bool IsJavaScriptIdentifier(const FormatToken ,
+  bool isJavaScriptIdentifier(const FormatToken ,
   bool AcceptIdentifierName = true) const {
 // Based on the list of JavaScript & TypeScript keywords here:
 // 
https://github.com/microsoft/TypeScript/blob/main/src/compiler/scanner.ts#L74
+if (Tok.isAccessSpecifierKeyword())
+  return false;
 switch (Tok.Tok.getKind()) {
 case tok::kw_break:
 case tok::kw_case:
@@ -1679,9 +1685,6 @@ struct AdditionalKeywords {
 case tok::kw_import:
 case tok::kw_module:
 case tok::kw_new:
-case tok::kw_private:
-case tok::kw_protected:
-case tok::kw_public:
 case tok::kw_return:
 case tok::kw_static:
 case tok::kw_switch:
@@ -1724,6 +1727,8 @@ struct AdditionalKeywords {
   /// Returns \c true if \p Tok is a C# keyword, returns
   /// \c false if it is a anything else.
   bool isCSharpKeyword(const FormatToken ) const {
+if (Tok.isAccessSpecifierKeyword())
+  return true;
 switch (Tok.Tok.getKind()) {
 case tok::kw_bool:
 case tok::kw_break:
@@ -1750,9 +1755,6 @@ struct AdditionalKeywords {
 case tok::kw_namespace:
 case tok::kw_new:
 case tok::kw_operator:
-case tok::kw_private:
-case tok::kw_protected:
-case tok::kw_public:
 case tok::kw_return:
 case tok::kw_short:
 case tok::kw_sizeof:
diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 1332445070314..5a256fc7ebd9f 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -647,8 +647,8 @@ class AnnotatingParser {
   return true;
 
 // Limit this to being an access modifier that follows.
-if (AttrTok->isOneOf(tok::kw_public, tok::kw_private, tok::kw_protected,
- tok::comment, tok::kw_class, tok::kw_static,
+if (AttrTok->isAccessSpecifierKeyword() ||
+AttrTok->isOneOf(tok::comment, tok::kw_class, tok::kw_static,
  tok::l_square, Keywords.kw_internal)) {
   return true;
 }
@@ -1419,7 +1419,7 @@ class AnnotatingParser {
 Tok->setType(TT_CtorInitializerColon);
 } else {
   Tok->setType(TT_InheritanceColon);
-  if (Prev->isOneOf(tok::kw_public, tok::kw_private, 
tok::kw_protected))
+  if (Prev->isAccessSpecifierKeyword())
 Line.Type = LT_AccessModifier;
 }
   } else if (canBeObjCSelectorComponent(*Tok->Previous) && Tok->Next &&
@@ -2333,7 +2333,7 @@ class AnnotatingParser {
   if (Current.Previous) {
 bool IsIdentifier =
 Style.isJavaScript()
-? Keywords.IsJavaScriptIdentifier(
+? Keywords.isJavaScriptIdentifier(
   *Current.Previous, /* AcceptIdentifierName= */ true)
 : Current.Previous->is(tok::identifier);
 if (IsIdentifier ||
@@ -4948,11 +4948,11 @@ bool TokenAnnotator::spaceRequiredBefore(const 
AnnotatedLine ,
 
 // space between method modifier and opening parenthesis of a tuple return
 // type
-if (Left.isOneOf(tok::kw_public, tok::kw_private, tok::kw_protected,
- tok::kw_virtual, tok::kw_extern, tok::kw_static,
- Keywords.kw_internal, Keywords.kw_abstract,
- Keywords.kw_sealed, Keywords.kw_override,
-   

[clang] 527e732 - [clang-format][NFC] Suppress diagnostic noise in GetStyleOfFile test

2024-06-16 Thread Owen Pan via cfe-commits

Author: Owen Pan
Date: 2024-06-16T14:56:02-07:00
New Revision: 527e7328607ea0a55855e53a59c5030a7d07a554

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

LOG: [clang-format][NFC] Suppress diagnostic noise in GetStyleOfFile test

Added: 


Modified: 
clang/unittests/Format/ConfigParseTest.cpp

Removed: 




diff  --git a/clang/unittests/Format/ConfigParseTest.cpp 
b/clang/unittests/Format/ConfigParseTest.cpp
index 2513ab3939595..aded3ed2a6596 100644
--- a/clang/unittests/Format/ConfigParseTest.cpp
+++ b/clang/unittests/Format/ConfigParseTest.cpp
@@ -15,6 +15,7 @@ namespace clang {
 namespace format {
 namespace {
 
+void dropDiagnosticHandler(const llvm::SMDiagnostic &, void *) {}
 FormatStyle getGoogleStyle() { return getGoogleStyle(FormatStyle::LK_Cpp); }
 
 #define EXPECT_ALL_STYLES_EQUAL(Styles)
\
@@ -1240,7 +1241,8 @@ TEST(ConfigParseTest, GetStyleOfFile) {
   llvm::consumeError(Style4.takeError());
 
   // Test 5: error on invalid yaml on command line
-  auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", 
);
+  auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", ,
+ /*AllowUnknownOptions=*/false, dropDiagnosticHandler);
   ASSERT_FALSE((bool)Style5);
   llvm::consumeError(Style5.takeError());
 
@@ -1256,11 +1258,13 @@ TEST(ConfigParseTest, GetStyleOfFile) {
   "InvalidKey: 
InvalidValue")));
   ASSERT_TRUE(
   FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int 
i;")));
-  auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", );
+  auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", ,
+  /*AllowUnknownOptions=*/false, 
dropDiagnosticHandler);
   ASSERT_FALSE((bool)Style7a);
   llvm::consumeError(Style7a.takeError());
 
-  auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", , true);
+  auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", ,
+  /*AllowUnknownOptions=*/true, dropDiagnosticHandler);
   ASSERT_TRUE((bool)Style7b);
 
   // Test 8: inferred per-language defaults apply.
@@ -1466,8 +1470,7 @@ TEST(ConfigParseTest, GetStyleOutput) {
   // Suppress stderr.
   testing::internal::CaptureStderr();
   Style = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", ,
-   /*AllowUnknownOptions=*/true,
-   [](const llvm::SMDiagnostic &, void *) {});
+   /*AllowUnknownOptions=*/true, dropDiagnosticHandler);
   Output = testing::internal::GetCapturedStderr();
   ASSERT_TRUE((bool)Style);
   ASSERT_TRUE(Output.empty());



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


[clang] [clang-format] Add DiagHandler parameter to format::getStyle() (PR #91317)

2024-06-16 Thread Owen Pan via cfe-commits

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


[clang] [clang-format] Handle AttributeMacro before access modifiers (PR #95634)

2024-06-16 Thread Owen Pan via cfe-commits

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


[clang] [clang-format] Handle Verilog delay control (PR #95703)

2024-06-16 Thread Owen Pan via cfe-commits

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


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


[clang] [clang-format] Handle AttributeMacro before access modifiers (PR #95503)

2024-06-16 Thread Owen Pan via cfe-commits

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


[clang] [clang-format] Handle AttributeMacro before access modifiers (PR #95634)

2024-06-16 Thread Owen Pan via cfe-commits

https://github.com/owenca updated 
https://github.com/llvm/llvm-project/pull/95634

>From 1c4ab4a5fd869de44795abd48bbaa43176e7275e Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Fri, 14 Jun 2024 23:36:58 -0700
Subject: [PATCH 1/5] [clang-format] Handle AttributeMacro before access
 modifiers

Closes #95094.
---
 clang/lib/Format/TokenAnnotator.cpp |  7 -
 clang/lib/Format/TokenAnnotator.h   |  1 +
 clang/lib/Format/UnwrappedLineFormatter.cpp | 35 ++---
 clang/unittests/Format/FormatTest.cpp   | 15 +
 4 files changed, 39 insertions(+), 19 deletions(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 1fe3b61a5a81f..ff00e772a75f4 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1970,6 +1970,7 @@ class AnnotatingParser {
   }
 }
 
+bool SeenAccessModifier = false;
 bool KeywordVirtualFound = false;
 bool ImportStatement = false;
 
@@ -1978,7 +1979,9 @@ class AnnotatingParser {
   ImportStatement = true;
 
 while (CurrentToken) {
-  if (CurrentToken->is(tok::kw_virtual))
+  if (CurrentToken->isAccessSpecifier())
+SeenAccessModifier = true;
+  else if (CurrentToken->is(tok::kw_virtual))
 KeywordVirtualFound = true;
   if (Style.isJavaScript()) {
 // export {...} from '...';
@@ -1998,6 +2001,8 @@ class AnnotatingParser {
   if (!consumeToken())
 return LT_Invalid;
 }
+if (SeenAccessModifier)
+  return LT_AccessModifier;
 if (KeywordVirtualFound)
   return LT_VirtualFunctionDecl;
 if (ImportStatement)
diff --git a/clang/lib/Format/TokenAnnotator.h 
b/clang/lib/Format/TokenAnnotator.h
index d19d3d061e40c..136880eca718b 100644
--- a/clang/lib/Format/TokenAnnotator.h
+++ b/clang/lib/Format/TokenAnnotator.h
@@ -22,6 +22,7 @@ namespace format {
 
 enum LineType {
   LT_Invalid,
+  LT_AccessModifier, // Contains public/protected/private followed by colon.
   LT_ImportStatement,
   LT_ObjCDecl, // An @interface, @implementation, or @protocol line.
   LT_ObjCMethodDecl,
diff --git a/clang/lib/Format/UnwrappedLineFormatter.cpp 
b/clang/lib/Format/UnwrappedLineFormatter.cpp
index 4d53361aaf333..729f3d78f4a35 100644
--- a/clang/lib/Format/UnwrappedLineFormatter.cpp
+++ b/clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -57,7 +57,7 @@ class LevelIndentTracker {
   /// Update the indent state given that \p Line is going to be formatted
   /// next.
   void nextLine(const AnnotatedLine ) {
-Offset = getIndentOffset(*Line.First);
+Offset = getIndentOffset(Line);
 // Update the indent level cache size so that we can rely on it
 // having the right size in adjustToUnmodifiedline.
 if (Line.Level >= IndentForLevel.size())
@@ -111,42 +111,41 @@ class LevelIndentTracker {
   ///
   /// For example, 'public:' labels in classes are offset by 1 or 2
   /// characters to the left from their level.
-  int getIndentOffset(const FormatToken ) {
+  int getIndentOffset(const AnnotatedLine ) {
 if (Style.Language == FormatStyle::LK_Java || Style.isJavaScript() ||
 Style.isCSharp()) {
   return 0;
 }
 
-auto IsAccessModifier = [this, ]() {
-  if (RootToken.isAccessSpecifier(Style.isCpp())) {
+auto IsAccessModifier = [&](const FormatToken ) {
+  if (Line.Type == LT_AccessModifier || RootToken.isObjCAccessSpecifier())
 return true;
-  } else if (RootToken.isObjCAccessSpecifier()) {
-return true;
-  }
+
+  const auto *Next = RootToken.Next;
+
   // Handle Qt signals.
-  else if (RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) &&
-   RootToken.Next && RootToken.Next->is(tok::colon)) {
-return true;
-  } else if (RootToken.Next &&
- RootToken.Next->isOneOf(Keywords.kw_slots,
- Keywords.kw_qslots) &&
- RootToken.Next->Next && RootToken.Next->Next->is(tok::colon)) 
{
+  if (RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) &&
+  Next && Next->is(tok::colon)) {
 return true;
   }
-  // Handle malformed access specifier e.g. 'private' without trailing ':'.
-  else if (!RootToken.Next && RootToken.isAccessSpecifier(false)) {
+
+  if (Next && Next->isOneOf(Keywords.kw_slots, Keywords.kw_qslots) &&
+  Next->Next && Next->Next->is(tok::colon)) {
 return true;
   }
-  return false;
+
+  // Handle malformed access specifier e.g. 'private' without trailing ':'.
+  return !Next && RootToken.isAccessSpecifier(false);
 };
 
-if (IsAccessModifier()) {
+if (IsAccessModifier(*Line.First)) {
   // The AccessModifierOffset may be overridden by IndentAccessModifiers,
   // in which case we take a negative value of the IndentWidth to simulate
   // the upper indent level.
   return Style.IndentAccessModifiers ? 

[clang] [clang-format] Handle AttributeMacro before access modifiers (PR #95634)

2024-06-16 Thread Owen Pan via cfe-commits

https://github.com/owenca updated 
https://github.com/llvm/llvm-project/pull/95634

>From 1c4ab4a5fd869de44795abd48bbaa43176e7275e Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Fri, 14 Jun 2024 23:36:58 -0700
Subject: [PATCH 1/4] [clang-format] Handle AttributeMacro before access
 modifiers

Closes #95094.
---
 clang/lib/Format/TokenAnnotator.cpp |  7 -
 clang/lib/Format/TokenAnnotator.h   |  1 +
 clang/lib/Format/UnwrappedLineFormatter.cpp | 35 ++---
 clang/unittests/Format/FormatTest.cpp   | 15 +
 4 files changed, 39 insertions(+), 19 deletions(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 1fe3b61a5a81f..ff00e772a75f4 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1970,6 +1970,7 @@ class AnnotatingParser {
   }
 }
 
+bool SeenAccessModifier = false;
 bool KeywordVirtualFound = false;
 bool ImportStatement = false;
 
@@ -1978,7 +1979,9 @@ class AnnotatingParser {
   ImportStatement = true;
 
 while (CurrentToken) {
-  if (CurrentToken->is(tok::kw_virtual))
+  if (CurrentToken->isAccessSpecifier())
+SeenAccessModifier = true;
+  else if (CurrentToken->is(tok::kw_virtual))
 KeywordVirtualFound = true;
   if (Style.isJavaScript()) {
 // export {...} from '...';
@@ -1998,6 +2001,8 @@ class AnnotatingParser {
   if (!consumeToken())
 return LT_Invalid;
 }
+if (SeenAccessModifier)
+  return LT_AccessModifier;
 if (KeywordVirtualFound)
   return LT_VirtualFunctionDecl;
 if (ImportStatement)
diff --git a/clang/lib/Format/TokenAnnotator.h 
b/clang/lib/Format/TokenAnnotator.h
index d19d3d061e40c..136880eca718b 100644
--- a/clang/lib/Format/TokenAnnotator.h
+++ b/clang/lib/Format/TokenAnnotator.h
@@ -22,6 +22,7 @@ namespace format {
 
 enum LineType {
   LT_Invalid,
+  LT_AccessModifier, // Contains public/protected/private followed by colon.
   LT_ImportStatement,
   LT_ObjCDecl, // An @interface, @implementation, or @protocol line.
   LT_ObjCMethodDecl,
diff --git a/clang/lib/Format/UnwrappedLineFormatter.cpp 
b/clang/lib/Format/UnwrappedLineFormatter.cpp
index 4d53361aaf333..729f3d78f4a35 100644
--- a/clang/lib/Format/UnwrappedLineFormatter.cpp
+++ b/clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -57,7 +57,7 @@ class LevelIndentTracker {
   /// Update the indent state given that \p Line is going to be formatted
   /// next.
   void nextLine(const AnnotatedLine ) {
-Offset = getIndentOffset(*Line.First);
+Offset = getIndentOffset(Line);
 // Update the indent level cache size so that we can rely on it
 // having the right size in adjustToUnmodifiedline.
 if (Line.Level >= IndentForLevel.size())
@@ -111,42 +111,41 @@ class LevelIndentTracker {
   ///
   /// For example, 'public:' labels in classes are offset by 1 or 2
   /// characters to the left from their level.
-  int getIndentOffset(const FormatToken ) {
+  int getIndentOffset(const AnnotatedLine ) {
 if (Style.Language == FormatStyle::LK_Java || Style.isJavaScript() ||
 Style.isCSharp()) {
   return 0;
 }
 
-auto IsAccessModifier = [this, ]() {
-  if (RootToken.isAccessSpecifier(Style.isCpp())) {
+auto IsAccessModifier = [&](const FormatToken ) {
+  if (Line.Type == LT_AccessModifier || RootToken.isObjCAccessSpecifier())
 return true;
-  } else if (RootToken.isObjCAccessSpecifier()) {
-return true;
-  }
+
+  const auto *Next = RootToken.Next;
+
   // Handle Qt signals.
-  else if (RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) &&
-   RootToken.Next && RootToken.Next->is(tok::colon)) {
-return true;
-  } else if (RootToken.Next &&
- RootToken.Next->isOneOf(Keywords.kw_slots,
- Keywords.kw_qslots) &&
- RootToken.Next->Next && RootToken.Next->Next->is(tok::colon)) 
{
+  if (RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) &&
+  Next && Next->is(tok::colon)) {
 return true;
   }
-  // Handle malformed access specifier e.g. 'private' without trailing ':'.
-  else if (!RootToken.Next && RootToken.isAccessSpecifier(false)) {
+
+  if (Next && Next->isOneOf(Keywords.kw_slots, Keywords.kw_qslots) &&
+  Next->Next && Next->Next->is(tok::colon)) {
 return true;
   }
-  return false;
+
+  // Handle malformed access specifier e.g. 'private' without trailing ':'.
+  return !Next && RootToken.isAccessSpecifier(false);
 };
 
-if (IsAccessModifier()) {
+if (IsAccessModifier(*Line.First)) {
   // The AccessModifierOffset may be overridden by IndentAccessModifiers,
   // in which case we take a negative value of the IndentWidth to simulate
   // the upper indent level.
   return Style.IndentAccessModifiers ? 

[clang] [clang-format] Handle AttributeMacro before access modifiers (PR #95634)

2024-06-16 Thread Owen Pan via cfe-commits

https://github.com/owenca updated 
https://github.com/llvm/llvm-project/pull/95634

>From 1c4ab4a5fd869de44795abd48bbaa43176e7275e Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Fri, 14 Jun 2024 23:36:58 -0700
Subject: [PATCH 1/3] [clang-format] Handle AttributeMacro before access
 modifiers

Closes #95094.
---
 clang/lib/Format/TokenAnnotator.cpp |  7 -
 clang/lib/Format/TokenAnnotator.h   |  1 +
 clang/lib/Format/UnwrappedLineFormatter.cpp | 35 ++---
 clang/unittests/Format/FormatTest.cpp   | 15 +
 4 files changed, 39 insertions(+), 19 deletions(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 1fe3b61a5a81f..ff00e772a75f4 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1970,6 +1970,7 @@ class AnnotatingParser {
   }
 }
 
+bool SeenAccessModifier = false;
 bool KeywordVirtualFound = false;
 bool ImportStatement = false;
 
@@ -1978,7 +1979,9 @@ class AnnotatingParser {
   ImportStatement = true;
 
 while (CurrentToken) {
-  if (CurrentToken->is(tok::kw_virtual))
+  if (CurrentToken->isAccessSpecifier())
+SeenAccessModifier = true;
+  else if (CurrentToken->is(tok::kw_virtual))
 KeywordVirtualFound = true;
   if (Style.isJavaScript()) {
 // export {...} from '...';
@@ -1998,6 +2001,8 @@ class AnnotatingParser {
   if (!consumeToken())
 return LT_Invalid;
 }
+if (SeenAccessModifier)
+  return LT_AccessModifier;
 if (KeywordVirtualFound)
   return LT_VirtualFunctionDecl;
 if (ImportStatement)
diff --git a/clang/lib/Format/TokenAnnotator.h 
b/clang/lib/Format/TokenAnnotator.h
index d19d3d061e40c..136880eca718b 100644
--- a/clang/lib/Format/TokenAnnotator.h
+++ b/clang/lib/Format/TokenAnnotator.h
@@ -22,6 +22,7 @@ namespace format {
 
 enum LineType {
   LT_Invalid,
+  LT_AccessModifier, // Contains public/protected/private followed by colon.
   LT_ImportStatement,
   LT_ObjCDecl, // An @interface, @implementation, or @protocol line.
   LT_ObjCMethodDecl,
diff --git a/clang/lib/Format/UnwrappedLineFormatter.cpp 
b/clang/lib/Format/UnwrappedLineFormatter.cpp
index 4d53361aaf333..729f3d78f4a35 100644
--- a/clang/lib/Format/UnwrappedLineFormatter.cpp
+++ b/clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -57,7 +57,7 @@ class LevelIndentTracker {
   /// Update the indent state given that \p Line is going to be formatted
   /// next.
   void nextLine(const AnnotatedLine ) {
-Offset = getIndentOffset(*Line.First);
+Offset = getIndentOffset(Line);
 // Update the indent level cache size so that we can rely on it
 // having the right size in adjustToUnmodifiedline.
 if (Line.Level >= IndentForLevel.size())
@@ -111,42 +111,41 @@ class LevelIndentTracker {
   ///
   /// For example, 'public:' labels in classes are offset by 1 or 2
   /// characters to the left from their level.
-  int getIndentOffset(const FormatToken ) {
+  int getIndentOffset(const AnnotatedLine ) {
 if (Style.Language == FormatStyle::LK_Java || Style.isJavaScript() ||
 Style.isCSharp()) {
   return 0;
 }
 
-auto IsAccessModifier = [this, ]() {
-  if (RootToken.isAccessSpecifier(Style.isCpp())) {
+auto IsAccessModifier = [&](const FormatToken ) {
+  if (Line.Type == LT_AccessModifier || RootToken.isObjCAccessSpecifier())
 return true;
-  } else if (RootToken.isObjCAccessSpecifier()) {
-return true;
-  }
+
+  const auto *Next = RootToken.Next;
+
   // Handle Qt signals.
-  else if (RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) &&
-   RootToken.Next && RootToken.Next->is(tok::colon)) {
-return true;
-  } else if (RootToken.Next &&
- RootToken.Next->isOneOf(Keywords.kw_slots,
- Keywords.kw_qslots) &&
- RootToken.Next->Next && RootToken.Next->Next->is(tok::colon)) 
{
+  if (RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) &&
+  Next && Next->is(tok::colon)) {
 return true;
   }
-  // Handle malformed access specifier e.g. 'private' without trailing ':'.
-  else if (!RootToken.Next && RootToken.isAccessSpecifier(false)) {
+
+  if (Next && Next->isOneOf(Keywords.kw_slots, Keywords.kw_qslots) &&
+  Next->Next && Next->Next->is(tok::colon)) {
 return true;
   }
-  return false;
+
+  // Handle malformed access specifier e.g. 'private' without trailing ':'.
+  return !Next && RootToken.isAccessSpecifier(false);
 };
 
-if (IsAccessModifier()) {
+if (IsAccessModifier(*Line.First)) {
   // The AccessModifierOffset may be overridden by IndentAccessModifiers,
   // in which case we take a negative value of the IndentWidth to simulate
   // the upper indent level.
   return Style.IndentAccessModifiers ? 

[clang] [clang-format] Handle AttributeMacro before access modifiers (PR #95634)

2024-06-15 Thread Owen Pan via cfe-commits

https://github.com/owenca updated 
https://github.com/llvm/llvm-project/pull/95634

>From 1c4ab4a5fd869de44795abd48bbaa43176e7275e Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Fri, 14 Jun 2024 23:36:58 -0700
Subject: [PATCH 1/2] [clang-format] Handle AttributeMacro before access
 modifiers

Closes #95094.
---
 clang/lib/Format/TokenAnnotator.cpp |  7 -
 clang/lib/Format/TokenAnnotator.h   |  1 +
 clang/lib/Format/UnwrappedLineFormatter.cpp | 35 ++---
 clang/unittests/Format/FormatTest.cpp   | 15 +
 4 files changed, 39 insertions(+), 19 deletions(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 1fe3b61a5a81f..ff00e772a75f4 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1970,6 +1970,7 @@ class AnnotatingParser {
   }
 }
 
+bool SeenAccessModifier = false;
 bool KeywordVirtualFound = false;
 bool ImportStatement = false;
 
@@ -1978,7 +1979,9 @@ class AnnotatingParser {
   ImportStatement = true;
 
 while (CurrentToken) {
-  if (CurrentToken->is(tok::kw_virtual))
+  if (CurrentToken->isAccessSpecifier())
+SeenAccessModifier = true;
+  else if (CurrentToken->is(tok::kw_virtual))
 KeywordVirtualFound = true;
   if (Style.isJavaScript()) {
 // export {...} from '...';
@@ -1998,6 +2001,8 @@ class AnnotatingParser {
   if (!consumeToken())
 return LT_Invalid;
 }
+if (SeenAccessModifier)
+  return LT_AccessModifier;
 if (KeywordVirtualFound)
   return LT_VirtualFunctionDecl;
 if (ImportStatement)
diff --git a/clang/lib/Format/TokenAnnotator.h 
b/clang/lib/Format/TokenAnnotator.h
index d19d3d061e40c..136880eca718b 100644
--- a/clang/lib/Format/TokenAnnotator.h
+++ b/clang/lib/Format/TokenAnnotator.h
@@ -22,6 +22,7 @@ namespace format {
 
 enum LineType {
   LT_Invalid,
+  LT_AccessModifier, // Contains public/protected/private followed by colon.
   LT_ImportStatement,
   LT_ObjCDecl, // An @interface, @implementation, or @protocol line.
   LT_ObjCMethodDecl,
diff --git a/clang/lib/Format/UnwrappedLineFormatter.cpp 
b/clang/lib/Format/UnwrappedLineFormatter.cpp
index 4d53361aaf333..729f3d78f4a35 100644
--- a/clang/lib/Format/UnwrappedLineFormatter.cpp
+++ b/clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -57,7 +57,7 @@ class LevelIndentTracker {
   /// Update the indent state given that \p Line is going to be formatted
   /// next.
   void nextLine(const AnnotatedLine ) {
-Offset = getIndentOffset(*Line.First);
+Offset = getIndentOffset(Line);
 // Update the indent level cache size so that we can rely on it
 // having the right size in adjustToUnmodifiedline.
 if (Line.Level >= IndentForLevel.size())
@@ -111,42 +111,41 @@ class LevelIndentTracker {
   ///
   /// For example, 'public:' labels in classes are offset by 1 or 2
   /// characters to the left from their level.
-  int getIndentOffset(const FormatToken ) {
+  int getIndentOffset(const AnnotatedLine ) {
 if (Style.Language == FormatStyle::LK_Java || Style.isJavaScript() ||
 Style.isCSharp()) {
   return 0;
 }
 
-auto IsAccessModifier = [this, ]() {
-  if (RootToken.isAccessSpecifier(Style.isCpp())) {
+auto IsAccessModifier = [&](const FormatToken ) {
+  if (Line.Type == LT_AccessModifier || RootToken.isObjCAccessSpecifier())
 return true;
-  } else if (RootToken.isObjCAccessSpecifier()) {
-return true;
-  }
+
+  const auto *Next = RootToken.Next;
+
   // Handle Qt signals.
-  else if (RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) &&
-   RootToken.Next && RootToken.Next->is(tok::colon)) {
-return true;
-  } else if (RootToken.Next &&
- RootToken.Next->isOneOf(Keywords.kw_slots,
- Keywords.kw_qslots) &&
- RootToken.Next->Next && RootToken.Next->Next->is(tok::colon)) 
{
+  if (RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) &&
+  Next && Next->is(tok::colon)) {
 return true;
   }
-  // Handle malformed access specifier e.g. 'private' without trailing ':'.
-  else if (!RootToken.Next && RootToken.isAccessSpecifier(false)) {
+
+  if (Next && Next->isOneOf(Keywords.kw_slots, Keywords.kw_qslots) &&
+  Next->Next && Next->Next->is(tok::colon)) {
 return true;
   }
-  return false;
+
+  // Handle malformed access specifier e.g. 'private' without trailing ':'.
+  return !Next && RootToken.isAccessSpecifier(false);
 };
 
-if (IsAccessModifier()) {
+if (IsAccessModifier(*Line.First)) {
   // The AccessModifierOffset may be overridden by IndentAccessModifiers,
   // in which case we take a negative value of the IndentWidth to simulate
   // the upper indent level.
   return Style.IndentAccessModifiers ? 

[clang] [clang-format] Handle AttributeMacro before access modifiers (PR #95503)

2024-06-15 Thread Owen Pan via cfe-commits


@@ -57,7 +57,10 @@ class LevelIndentTracker {
   /// Update the indent state given that \p Line is going to be formatted
   /// next.
   void nextLine(const AnnotatedLine ) {
-Offset = getIndentOffset(*Line.First);
+const auto *Tok = Line.First;
+if (Tok->is(TT_AttributeMacro) && Tok->Next)

owenca wrote:

I thought of it but decided to not bother because it would be rare and looping 
through all `AttributeMacro` prefixes would still leave comments and 
function-like macros unsupported. See a better solution in #95634.

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


[clang] [clang-format] Handle AttributeMacro before access modifiers (PR #95634)

2024-06-15 Thread Owen Pan via cfe-commits

https://github.com/owenca created 
https://github.com/llvm/llvm-project/pull/95634

Closes #95094.

>From 1c4ab4a5fd869de44795abd48bbaa43176e7275e Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Fri, 14 Jun 2024 23:36:58 -0700
Subject: [PATCH] [clang-format] Handle AttributeMacro before access modifiers

Closes #95094.
---
 clang/lib/Format/TokenAnnotator.cpp |  7 -
 clang/lib/Format/TokenAnnotator.h   |  1 +
 clang/lib/Format/UnwrappedLineFormatter.cpp | 35 ++---
 clang/unittests/Format/FormatTest.cpp   | 15 +
 4 files changed, 39 insertions(+), 19 deletions(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 1fe3b61a5a81f..ff00e772a75f4 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1970,6 +1970,7 @@ class AnnotatingParser {
   }
 }
 
+bool SeenAccessModifier = false;
 bool KeywordVirtualFound = false;
 bool ImportStatement = false;
 
@@ -1978,7 +1979,9 @@ class AnnotatingParser {
   ImportStatement = true;
 
 while (CurrentToken) {
-  if (CurrentToken->is(tok::kw_virtual))
+  if (CurrentToken->isAccessSpecifier())
+SeenAccessModifier = true;
+  else if (CurrentToken->is(tok::kw_virtual))
 KeywordVirtualFound = true;
   if (Style.isJavaScript()) {
 // export {...} from '...';
@@ -1998,6 +2001,8 @@ class AnnotatingParser {
   if (!consumeToken())
 return LT_Invalid;
 }
+if (SeenAccessModifier)
+  return LT_AccessModifier;
 if (KeywordVirtualFound)
   return LT_VirtualFunctionDecl;
 if (ImportStatement)
diff --git a/clang/lib/Format/TokenAnnotator.h 
b/clang/lib/Format/TokenAnnotator.h
index d19d3d061e40c..136880eca718b 100644
--- a/clang/lib/Format/TokenAnnotator.h
+++ b/clang/lib/Format/TokenAnnotator.h
@@ -22,6 +22,7 @@ namespace format {
 
 enum LineType {
   LT_Invalid,
+  LT_AccessModifier, // Contains public/protected/private followed by colon.
   LT_ImportStatement,
   LT_ObjCDecl, // An @interface, @implementation, or @protocol line.
   LT_ObjCMethodDecl,
diff --git a/clang/lib/Format/UnwrappedLineFormatter.cpp 
b/clang/lib/Format/UnwrappedLineFormatter.cpp
index 4d53361aaf333..729f3d78f4a35 100644
--- a/clang/lib/Format/UnwrappedLineFormatter.cpp
+++ b/clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -57,7 +57,7 @@ class LevelIndentTracker {
   /// Update the indent state given that \p Line is going to be formatted
   /// next.
   void nextLine(const AnnotatedLine ) {
-Offset = getIndentOffset(*Line.First);
+Offset = getIndentOffset(Line);
 // Update the indent level cache size so that we can rely on it
 // having the right size in adjustToUnmodifiedline.
 if (Line.Level >= IndentForLevel.size())
@@ -111,42 +111,41 @@ class LevelIndentTracker {
   ///
   /// For example, 'public:' labels in classes are offset by 1 or 2
   /// characters to the left from their level.
-  int getIndentOffset(const FormatToken ) {
+  int getIndentOffset(const AnnotatedLine ) {
 if (Style.Language == FormatStyle::LK_Java || Style.isJavaScript() ||
 Style.isCSharp()) {
   return 0;
 }
 
-auto IsAccessModifier = [this, ]() {
-  if (RootToken.isAccessSpecifier(Style.isCpp())) {
+auto IsAccessModifier = [&](const FormatToken ) {
+  if (Line.Type == LT_AccessModifier || RootToken.isObjCAccessSpecifier())
 return true;
-  } else if (RootToken.isObjCAccessSpecifier()) {
-return true;
-  }
+
+  const auto *Next = RootToken.Next;
+
   // Handle Qt signals.
-  else if (RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) &&
-   RootToken.Next && RootToken.Next->is(tok::colon)) {
-return true;
-  } else if (RootToken.Next &&
- RootToken.Next->isOneOf(Keywords.kw_slots,
- Keywords.kw_qslots) &&
- RootToken.Next->Next && RootToken.Next->Next->is(tok::colon)) 
{
+  if (RootToken.isOneOf(Keywords.kw_signals, Keywords.kw_qsignals) &&
+  Next && Next->is(tok::colon)) {
 return true;
   }
-  // Handle malformed access specifier e.g. 'private' without trailing ':'.
-  else if (!RootToken.Next && RootToken.isAccessSpecifier(false)) {
+
+  if (Next && Next->isOneOf(Keywords.kw_slots, Keywords.kw_qslots) &&
+  Next->Next && Next->Next->is(tok::colon)) {
 return true;
   }
-  return false;
+
+  // Handle malformed access specifier e.g. 'private' without trailing ':'.
+  return !Next && RootToken.isAccessSpecifier(false);
 };
 
-if (IsAccessModifier()) {
+if (IsAccessModifier(*Line.First)) {
   // The AccessModifierOffset may be overridden by IndentAccessModifiers,
   // in which case we take a negative value of the IndentWidth to simulate
   // the upper indent level.
   return Style.IndentAccessModifiers ? 

[clang] [clang-format] Add DiagHandler parameter to format::getStyle() (PR #91317)

2024-06-14 Thread Owen Pan via cfe-commits

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


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


[clang] [clang-format] Add DiagHandler parameter to format::getStyle() (PR #91317)

2024-06-14 Thread Owen Pan via cfe-commits

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


[clang] [clang-format] Add DiagHandler parameter to format::getStyle() (PR #91317)

2024-06-14 Thread Owen Pan via cfe-commits

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


[clang] [clang-format] Add DiagHandler for getStyle function (PR #91317)

2024-06-14 Thread Owen Pan via cfe-commits

https://github.com/owenca updated 
https://github.com/llvm/llvm-project/pull/91317

>From c1e0ad6ee57a95fa4321bbe91aa754167da9fb3b Mon Sep 17 00:00:00 2001
From: Artem Sokolovskii 
Date: Tue, 7 May 2024 12:27:29 +0200
Subject: [PATCH 1/3] [clang-format] Add DiagHandler for getStyle function

It allows to control of error output for the function.
---
 clang/include/clang/Format/Format.h|  9 
 clang/lib/Format/Format.cpp| 25 +-
 clang/unittests/Format/ConfigParseTest.cpp | 21 ++
 3 files changed, 41 insertions(+), 14 deletions(-)

diff --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 4fd6e013df25b..3bbc362fc8bc7 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -5387,10 +5387,11 @@ extern const char *DefaultFallbackStyle;
 /// \returns FormatStyle as specified by ``StyleName``. If ``StyleName`` is
 /// "file" and no file is found, returns ``FallbackStyle``. If no style could 
be
 /// determined, returns an Error.
-Expected getStyle(StringRef StyleName, StringRef FileName,
-   StringRef FallbackStyle, StringRef Code = "",
-   llvm::vfs::FileSystem *FS = nullptr,
-   bool AllowUnknownOptions = false);
+Expected
+getStyle(StringRef StyleName, StringRef FileName, StringRef FallbackStyle,
+ StringRef Code = "", llvm::vfs::FileSystem *FS = nullptr,
+ bool AllowUnknownOptions = false,
+ llvm::SourceMgr::DiagHandlerTy DiagHandler = nullptr);
 
 // Guesses the language from the ``FileName`` and ``Code`` to be formatted.
 // Defaults to FormatStyle::LK_Cpp.
diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index c015e03fa15e7..b1def18f9b7da 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -3946,20 +3946,23 @@ const char *DefaultFallbackStyle = "LLVM";
 
 llvm::ErrorOr>
 loadAndParseConfigFile(StringRef ConfigFile, llvm::vfs::FileSystem *FS,
-   FormatStyle *Style, bool AllowUnknownOptions) {
+   FormatStyle *Style, bool AllowUnknownOptions,
+   llvm::SourceMgr::DiagHandlerTy DiagHandler) {
   llvm::ErrorOr> Text =
   FS->getBufferForFile(ConfigFile.str());
   if (auto EC = Text.getError())
 return EC;
-  if (auto EC = parseConfiguration(*Text.get(), Style, AllowUnknownOptions))
+  if (auto EC = parseConfiguration(*Text.get(), Style, AllowUnknownOptions,
+   DiagHandler)) {
 return EC;
+  }
   return Text;
 }
 
-Expected getStyle(StringRef StyleName, StringRef FileName,
-   StringRef FallbackStyleName, StringRef Code,
-   llvm::vfs::FileSystem *FS,
-   bool AllowUnknownOptions) {
+Expected
+getStyle(StringRef StyleName, StringRef FileName, StringRef FallbackStyleName,
+ StringRef Code, llvm::vfs::FileSystem *FS, bool AllowUnknownOptions,
+ llvm::SourceMgr::DiagHandlerTy DiagHandler) {
   FormatStyle Style = getLLVMStyle(guessLanguage(FileName, Code));
   FormatStyle FallbackStyle = getNoStyle();
   if (!getPredefinedStyle(FallbackStyleName, Style.Language, ))
@@ -3972,7 +3975,7 @@ Expected getStyle(StringRef StyleName, 
StringRef FileName,
 StringRef Source = "";
 if (std::error_code ec =
 parseConfiguration(llvm::MemoryBufferRef(StyleName, Source), 
,
-   AllowUnknownOptions)) {
+   AllowUnknownOptions, DiagHandler)) {
   return make_string_error("Error parsing -style: " + ec.message());
 }
 
@@ -3992,7 +3995,8 @@ Expected getStyle(StringRef StyleName, 
StringRef FileName,
   StyleName.starts_with_insensitive("file:")) {
 auto ConfigFile = StyleName.substr(5);
 llvm::ErrorOr> Text =
-loadAndParseConfigFile(ConfigFile, FS, , AllowUnknownOptions);
+loadAndParseConfigFile(ConfigFile, FS, , AllowUnknownOptions,
+   DiagHandler);
 if (auto EC = Text.getError()) {
   return make_string_error("Error reading " + ConfigFile + ": " +
EC.message());
@@ -4032,7 +4036,7 @@ Expected getStyle(StringRef StyleName, 
StringRef FileName,
   auto applyChildFormatTexts = [&](FormatStyle *Style) {
 for (const auto  : llvm::reverse(ChildFormatTextToApply)) {
   auto EC = parseConfiguration(*MemBuf, Style, AllowUnknownOptions,
-   dropDiagnosticHandler);
+   DiagHandler ? DiagHandler : 
dropDiagnosticHandler);
   // It was already correctly parsed.
   assert(!EC);
   static_cast(EC);
@@ -4066,7 +4070,8 @@ Expected getStyle(StringRef StyleName, 
StringRef FileName,
   }
 
   llvm::ErrorOr> Text =
-  loadAndParseConfigFile(ConfigFile, FS, , AllowUnknownOptions);

[clang] [clang-format] Add DiagHandler for getStyle function (PR #91317)

2024-06-14 Thread Owen Pan via cfe-commits

https://github.com/owenca updated 
https://github.com/llvm/llvm-project/pull/91317

>From c1e0ad6ee57a95fa4321bbe91aa754167da9fb3b Mon Sep 17 00:00:00 2001
From: Artem Sokolovskii 
Date: Tue, 7 May 2024 12:27:29 +0200
Subject: [PATCH 1/2] [clang-format] Add DiagHandler for getStyle function

It allows to control of error output for the function.
---
 clang/include/clang/Format/Format.h|  9 
 clang/lib/Format/Format.cpp| 25 +-
 clang/unittests/Format/ConfigParseTest.cpp | 21 ++
 3 files changed, 41 insertions(+), 14 deletions(-)

diff --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 4fd6e013df25b..3bbc362fc8bc7 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -5387,10 +5387,11 @@ extern const char *DefaultFallbackStyle;
 /// \returns FormatStyle as specified by ``StyleName``. If ``StyleName`` is
 /// "file" and no file is found, returns ``FallbackStyle``. If no style could 
be
 /// determined, returns an Error.
-Expected getStyle(StringRef StyleName, StringRef FileName,
-   StringRef FallbackStyle, StringRef Code = "",
-   llvm::vfs::FileSystem *FS = nullptr,
-   bool AllowUnknownOptions = false);
+Expected
+getStyle(StringRef StyleName, StringRef FileName, StringRef FallbackStyle,
+ StringRef Code = "", llvm::vfs::FileSystem *FS = nullptr,
+ bool AllowUnknownOptions = false,
+ llvm::SourceMgr::DiagHandlerTy DiagHandler = nullptr);
 
 // Guesses the language from the ``FileName`` and ``Code`` to be formatted.
 // Defaults to FormatStyle::LK_Cpp.
diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index c015e03fa15e7..b1def18f9b7da 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -3946,20 +3946,23 @@ const char *DefaultFallbackStyle = "LLVM";
 
 llvm::ErrorOr>
 loadAndParseConfigFile(StringRef ConfigFile, llvm::vfs::FileSystem *FS,
-   FormatStyle *Style, bool AllowUnknownOptions) {
+   FormatStyle *Style, bool AllowUnknownOptions,
+   llvm::SourceMgr::DiagHandlerTy DiagHandler) {
   llvm::ErrorOr> Text =
   FS->getBufferForFile(ConfigFile.str());
   if (auto EC = Text.getError())
 return EC;
-  if (auto EC = parseConfiguration(*Text.get(), Style, AllowUnknownOptions))
+  if (auto EC = parseConfiguration(*Text.get(), Style, AllowUnknownOptions,
+   DiagHandler)) {
 return EC;
+  }
   return Text;
 }
 
-Expected getStyle(StringRef StyleName, StringRef FileName,
-   StringRef FallbackStyleName, StringRef Code,
-   llvm::vfs::FileSystem *FS,
-   bool AllowUnknownOptions) {
+Expected
+getStyle(StringRef StyleName, StringRef FileName, StringRef FallbackStyleName,
+ StringRef Code, llvm::vfs::FileSystem *FS, bool AllowUnknownOptions,
+ llvm::SourceMgr::DiagHandlerTy DiagHandler) {
   FormatStyle Style = getLLVMStyle(guessLanguage(FileName, Code));
   FormatStyle FallbackStyle = getNoStyle();
   if (!getPredefinedStyle(FallbackStyleName, Style.Language, ))
@@ -3972,7 +3975,7 @@ Expected getStyle(StringRef StyleName, 
StringRef FileName,
 StringRef Source = "";
 if (std::error_code ec =
 parseConfiguration(llvm::MemoryBufferRef(StyleName, Source), 
,
-   AllowUnknownOptions)) {
+   AllowUnknownOptions, DiagHandler)) {
   return make_string_error("Error parsing -style: " + ec.message());
 }
 
@@ -3992,7 +3995,8 @@ Expected getStyle(StringRef StyleName, 
StringRef FileName,
   StyleName.starts_with_insensitive("file:")) {
 auto ConfigFile = StyleName.substr(5);
 llvm::ErrorOr> Text =
-loadAndParseConfigFile(ConfigFile, FS, , AllowUnknownOptions);
+loadAndParseConfigFile(ConfigFile, FS, , AllowUnknownOptions,
+   DiagHandler);
 if (auto EC = Text.getError()) {
   return make_string_error("Error reading " + ConfigFile + ": " +
EC.message());
@@ -4032,7 +4036,7 @@ Expected getStyle(StringRef StyleName, 
StringRef FileName,
   auto applyChildFormatTexts = [&](FormatStyle *Style) {
 for (const auto  : llvm::reverse(ChildFormatTextToApply)) {
   auto EC = parseConfiguration(*MemBuf, Style, AllowUnknownOptions,
-   dropDiagnosticHandler);
+   DiagHandler ? DiagHandler : 
dropDiagnosticHandler);
   // It was already correctly parsed.
   assert(!EC);
   static_cast(EC);
@@ -4066,7 +4070,8 @@ Expected getStyle(StringRef StyleName, 
StringRef FileName,
   }
 
   llvm::ErrorOr> Text =
-  loadAndParseConfigFile(ConfigFile, FS, , AllowUnknownOptions);

[clang] [clang-format] Don't over-indent comment below unbraced body (PR #95354)

2024-06-14 Thread Owen Pan via cfe-commits

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


[clang] [clang-format] Add DiagHandler for getStyle function (PR #91317)

2024-06-14 Thread Owen Pan via cfe-commits


@@ -1452,6 +1452,35 @@ TEST(ConfigParseTest, GetStyleOfSpecificFile) {
   ASSERT_EQ(*Style, getGoogleStyle());
 }
 
+TEST(ConfigParseTest, GetStyleOutput) {
+// With output
+::testing::internal::CaptureStderr();
+llvm::vfs::InMemoryFileSystem FS;
+auto Style = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", 
, false);
+
+const std::string output = ::testing::internal::GetCapturedStderr();
+
+ASSERT_FALSE((bool)Style);
+ASSERT_FALSE(output.empty());
+llvm::consumeError(Style.takeError());

owenca wrote:

```suggestion
  llvm::vfs::InMemoryFileSystem FS;

  // Don't suppress output.
  testing::internal::CaptureStderr();
  auto Style = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", ,
/*AllowUnknownOptions=*/true);
  const auto output = testing::internal::GetCapturedStderr();
  ASSERT_TRUE((bool)Style);
  ASSERT_FALSE(output.empty());
```

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


[clang] [clang-format] Add DiagHandler for getStyle function (PR #91317)

2024-06-14 Thread Owen Pan via cfe-commits

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


[clang] [clang-format] Add DiagHandler for getStyle function (PR #91317)

2024-06-14 Thread Owen Pan via cfe-commits


@@ -1452,6 +1452,35 @@ TEST(ConfigParseTest, GetStyleOfSpecificFile) {
   ASSERT_EQ(*Style, getGoogleStyle());
 }
 
+TEST(ConfigParseTest, GetStyleOutput) {
+// With output
+::testing::internal::CaptureStderr();
+llvm::vfs::InMemoryFileSystem FS;
+auto Style = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", 
, false);
+
+const std::string output = ::testing::internal::GetCapturedStderr();
+
+ASSERT_FALSE((bool)Style);
+ASSERT_FALSE(output.empty());
+llvm::consumeError(Style.takeError());
+
+// Without output
+::testing::internal::CaptureStderr();
+auto Style1 = getStyle("{invalid_key=invalid_value}",
+   "a.h",
+   "LLVM",
+   "",
+   ,
+   false,
+   [](const llvm::SMDiagnostic &, void *) {});
+
+const std::string output1 = ::testing::internal::GetCapturedStderr();
+
+ASSERT_FALSE((bool)Style1);
+ASSERT_TRUE(output1.empty());
+llvm::consumeError(Style1.takeError());

owenca wrote:

```suggestion
  // Suppress stderr.
  testing::internal::CaptureStderr();
  auto Style1 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", ,
 /*AllowUnknownOptions=*/true,
 [](const llvm::SMDiagnostic &, void *) {});
  const auto output1 = testing::internal::GetCapturedStderr();
  ASSERT_TRUE((bool)Style1);
  ASSERT_TRUE(output1.empty());
```

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


[clang] [clang-format] Add DiagHandler for getStyle function (PR #91317)

2024-06-14 Thread Owen Pan via cfe-commits


@@ -1452,6 +1452,35 @@ TEST(ConfigParseTest, GetStyleOfSpecificFile) {
   ASSERT_EQ(*Style, getGoogleStyle());
 }
 
+TEST(ConfigParseTest, GetStyleOutput) {
+// With output
+::testing::internal::CaptureStderr();
+llvm::vfs::InMemoryFileSystem FS;
+auto Style = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", 
, false);
+
+const std::string output = ::testing::internal::GetCapturedStderr();
+
+ASSERT_FALSE((bool)Style);
+ASSERT_FALSE(output.empty());
+llvm::consumeError(Style.takeError());

owenca wrote:

IMO we don't need this test.

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


[clang] [clang-format] Add DiagHandler for getStyle function (PR #91317)

2024-06-14 Thread Owen Pan via cfe-commits


@@ -4027,12 +4031,10 @@ Expected getStyle(StringRef StyleName, 
StringRef FileName,
   // Reset possible inheritance
   Style.InheritsParentConfig = false;
 
-  auto dropDiagnosticHandler = [](const llvm::SMDiagnostic &, void *) {};
-

owenca wrote:

Sorry! We do need it.

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


[clang] [clang-format] Add DiagHandler for getStyle function (PR #91317)

2024-06-14 Thread Owen Pan via cfe-commits


@@ -4027,12 +4031,10 @@ Expected getStyle(StringRef StyleName, 
StringRef FileName,
   // Reset possible inheritance
   Style.InheritsParentConfig = false;
 
-  auto dropDiagnosticHandler = [](const llvm::SMDiagnostic &, void *) {};
-
   auto applyChildFormatTexts = [&](FormatStyle *Style) {
 for (const auto  : llvm::reverse(ChildFormatTextToApply)) {
   auto EC = parseConfiguration(*MemBuf, Style, AllowUnknownOptions,
-   dropDiagnosticHandler);
+   DiagHandler);

owenca wrote:

```cpp
   auto applyChildFormatTexts = [&](FormatStyle *Style) {
 for (const auto  : llvm::reverse(ChildFormatTextToApply)) {
-  auto EC = parseConfiguration(*MemBuf, Style, AllowUnknownOptions,
-   DiagHandler);
+  auto EC =
+  parseConfiguration(*MemBuf, Style, AllowUnknownOptions,
+ DiagHandler ? DiagHandler : 
dropDiagnosticHandler);
   // It was already correctly parsed.
   assert(!EC);
   static_cast(EC);
```

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


[clang] [clang-format] Don't count template template parameter as declaration (PR #95025)

2024-06-13 Thread Owen Pan via cfe-commits


@@ -1269,10 +1269,17 @@ class AnnotatingParser {
 if (CurrentToken && CurrentToken->is(tok::less)) {
   CurrentToken->setType(TT_TemplateOpener);
   next();
-  if (!parseAngle())
+  TemplateDeclarationDepth++;
+  if (!parseAngle()) {
+TemplateDeclarationDepth--;
 return false;
-  if (CurrentToken)
+  }
+  TemplateDeclarationDepth--;
+  if (CurrentToken &&
+  (TemplateDeclarationDepth == 0 ||
+   !CurrentToken->isOneOf(tok::kw_typename, tok::kw_class))) {

owenca wrote:

Actually, checking the nesting level of the template brackets like you did is 
easier to understand. You just don't need to check the type-parameter keys IMO. 
Below is a rewrite of the function based on your solution:
```cpp
$ git diff
diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 958b46c535a9..9be5c09a32dd 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1266,23 +1266,22 @@ private:
   }
 
   bool parseTemplateDeclaration() {
-if (CurrentToken && CurrentToken->is(tok::less)) {
-  CurrentToken->setType(TT_TemplateOpener);
-  next();
-  TemplateDeclarationDepth++;
-  if (!parseAngle()) {
-TemplateDeclarationDepth--;
-return false;
-  }
-  TemplateDeclarationDepth--;
-  if (CurrentToken &&
-  (TemplateDeclarationDepth == 0 ||
-   !CurrentToken->isOneOf(tok::kw_typename, tok::kw_class))) {
-CurrentToken->Previous->ClosesTemplateDeclaration = true;
-  }
-  return true;
-}
-return false;
+if (!CurrentToken || CurrentToken->isNot(tok::less))
+  return false;
+
+CurrentToken->setType(TT_TemplateOpener);
+next();
+
+TemplateDeclarationDepth++;
+const bool WellFormed = parseAngle();
+TemplateDeclarationDepth--;
+if (!WellFormed)
+  return false;
+
+if (CurrentToken && TemplateDeclarationDepth == 0)
+  CurrentToken->Previous->ClosesTemplateDeclaration = true;
+
+return true;
   }
 
   bool consumeToken() {
$ 
```

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


[clang] [clang-format] Handle AttributeMacro before access modifiers (PR #95503)

2024-06-13 Thread Owen Pan via cfe-commits

https://github.com/owenca created 
https://github.com/llvm/llvm-project/pull/95503

Closes #95094.

>From 6684ed759ce118bb28e9da22be51bcfece2a1909 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Thu, 13 Jun 2024 21:25:08 -0700
Subject: [PATCH] [clang-format] Handle AttributeMacro before access modifiers

Closes #95094.
---
 clang/lib/Format/UnwrappedLineFormatter.cpp |  5 -
 clang/unittests/Format/FormatTest.cpp   | 15 +++
 2 files changed, 19 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Format/UnwrappedLineFormatter.cpp 
b/clang/lib/Format/UnwrappedLineFormatter.cpp
index 4d53361aaf333..80ab9827b050c 100644
--- a/clang/lib/Format/UnwrappedLineFormatter.cpp
+++ b/clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -57,7 +57,10 @@ class LevelIndentTracker {
   /// Update the indent state given that \p Line is going to be formatted
   /// next.
   void nextLine(const AnnotatedLine ) {
-Offset = getIndentOffset(*Line.First);
+const auto *Tok = Line.First;
+if (Tok->is(TT_AttributeMacro) && Tok->Next)
+  Tok = Tok->Next;
+Offset = getIndentOffset(*Tok);
 // Update the indent level cache size so that we can rely on it
 // having the right size in adjustToUnmodifiedline.
 if (Line.Level >= IndentForLevel.size())
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index fb57333858529..2ca85c7b70e65 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -12912,6 +12912,15 @@ TEST_F(FormatTest, FormatsAccessModifiers) {
"  int j;\n"
"};",
Style);
+  Style.AttributeMacros.push_back("FOO");
+  Style.AttributeMacros.push_back("BAR");
+  verifyFormat("struct foo {\n"
+   "FOO private:\n"
+   "  int i;\n"
+   "BAR private:\n"
+   "  int j;\n"
+   "};",
+   Style);
 
   FormatStyle NoEmptyLines = getLLVMStyle();
   NoEmptyLines.MaxEmptyLinesToKeep = 0;
@@ -26130,6 +26139,12 @@ TEST_F(FormatTest, IndentAccessModifiers) {
"  int i;\n"
"};",
Style);
+  Style.AttributeMacros.push_back("FOO");
+  verifyFormat("class C {\n"
+   "   FOO public:\n"
+   "  int i;\n"
+   "};",
+   Style);
 }
 
 TEST_F(FormatTest, LimitlessStringsAndComments) {

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


[clang] [clang-format] Fix bad comment indentation before ifdef after braceless if (PR #94776)

2024-06-12 Thread Owen Pan via cfe-commits

owenca wrote:

@Erich-Reitz you were on the right track. See #95354.

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


[clang] [clang-format] Don't over-indent comment below unbraced body (PR #95354)

2024-06-12 Thread Owen Pan via cfe-commits

https://github.com/owenca created 
https://github.com/llvm/llvm-project/pull/95354

Fixes #45002.

>From 02f1731d57d40e51605f667c8a0b1223b159e645 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Wed, 12 Jun 2024 22:04:17 -0700
Subject: [PATCH] [clang-format] Don't overindent comment below unbraced body

Fixes #45002.
---
 clang/lib/Format/UnwrappedLineParser.cpp  |  5 
 clang/lib/Format/UnwrappedLineParser.h|  3 ++
 clang/unittests/Format/FormatTestComments.cpp | 30 +++
 3 files changed, 38 insertions(+)

diff --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 08387d2e08ee0..899e68eadf70e 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -112,6 +112,7 @@ class ScopedLineState {
 Parser.Line->PPLevel = PreBlockLine->PPLevel;
 Parser.Line->InPPDirective = PreBlockLine->InPPDirective;
 Parser.Line->InMacroBody = PreBlockLine->InMacroBody;
+Parser.Line->UnbracedBodyLevel = PreBlockLine->UnbracedBodyLevel;
   }
 
   ~ScopedLineState() {
@@ -2708,7 +2709,9 @@ void UnwrappedLineParser::parseUnbracedBody(bool 
CheckEOF) {
 
   addUnwrappedLine();
   ++Line->Level;
+  ++Line->UnbracedBodyLevel;
   parseStructuralElement();
+  --Line->UnbracedBodyLevel;
 
   if (Tok) {
 assert(!Line->InPPDirective);
@@ -4836,6 +4839,8 @@ void UnwrappedLineParser::readToken(int LevelDifference) {
   PPBranchLevel > 0) {
 Line->Level += PPBranchLevel;
   }
+  assert(Line->Level >= Line->UnbracedBodyLevel);
+  Line->Level -= Line->UnbracedBodyLevel;
   flushComments(isOnNewLine(*FormatTok));
   parsePPDirective();
   PreviousWasComment = FormatTok->is(tok::comment);
diff --git a/clang/lib/Format/UnwrappedLineParser.h 
b/clang/lib/Format/UnwrappedLineParser.h
index d7963a4211bb9..d5eeb3d57149c 100644
--- a/clang/lib/Format/UnwrappedLineParser.h
+++ b/clang/lib/Format/UnwrappedLineParser.h
@@ -49,6 +49,9 @@ struct UnwrappedLine {
   /// Whether it is part of a macro body.
   bool InMacroBody = false;
 
+  /// Nesting level of unbraced body of a control statement.
+  unsigned UnbracedBodyLevel = 0;
+
   bool MustBeDeclaration = false;
 
   /// Whether the parser has seen \c decltype(auto) in this line.
diff --git a/clang/unittests/Format/FormatTestComments.cpp 
b/clang/unittests/Format/FormatTestComments.cpp
index d2baace6a7d80..3e75707a9faec 100644
--- a/clang/unittests/Format/FormatTestComments.cpp
+++ b/clang/unittests/Format/FormatTestComments.cpp
@@ -1087,6 +1087,36 @@ TEST_F(FormatTestComments, 
KeepsLevelOfCommentBeforePPDirective) {
Style);
 }
 
+TEST_F(FormatTestComments, CommentsBetweenUnbracedBodyAndPPDirective) {
+  verifyFormat("{\n"
+   "  if (a)\n"
+   "f(); // comment\n"
+   "#define A\n"
+   "}");
+
+  verifyFormat("{\n"
+   "  while (a)\n"
+   "f();\n"
+   "// comment\n"
+   "#define A\n"
+   "}");
+
+  verifyNoChange("{\n"
+ "  if (a)\n"
+ "f();\n"
+ "  // comment\n"
+ "#define A\n"
+ "}");
+
+  verifyNoChange("{\n"
+ "  while (a)\n"
+ "if (b)\n"
+ "  f();\n"
+ "  // comment\n"
+ "#define A\n"
+ "}");
+}
+
 TEST_F(FormatTestComments, SplitsLongLinesInComments) {
   // FIXME: Do we need to fix up the "  */" at the end?
   // It doesn't look like any of our current logic triggers this.

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


[clang] [clang-format] Don't count template template parameter as declaration (PR #95025)

2024-06-12 Thread Owen Pan via cfe-commits


@@ -1269,10 +1269,17 @@ class AnnotatingParser {
 if (CurrentToken && CurrentToken->is(tok::less)) {
   CurrentToken->setType(TT_TemplateOpener);
   next();
-  if (!parseAngle())
+  TemplateDeclarationDepth++;
+  if (!parseAngle()) {
+TemplateDeclarationDepth--;
 return false;
-  if (CurrentToken)
+  }
+  TemplateDeclarationDepth--;
+  if (CurrentToken &&
+  (TemplateDeclarationDepth == 0 ||
+   !CurrentToken->isOneOf(tok::kw_typename, tok::kw_class))) {

owenca wrote:

> If parseAngle fails, wouldn't that cause InTemplateDeclaration to forever be 
> true? Is that not an issue?

If `parseAngle()` returns false, it probably means that the template decl is 
ill-formed. If so, it doesn't matter if `InTemplateDeclaration` is set to false?

An alternative solution:
```
-  bool parseTemplateDeclaration() {
-if (CurrentToken && CurrentToken->is(tok::less)) {
-  CurrentToken->setType(TT_TemplateOpener);
-  next();
-  if (!parseAngle())
-return false;
-  if (CurrentToken)
-CurrentToken->Previous->ClosesTemplateDeclaration = true;
-  return true;
-}
-return false;
+  bool parseTemplateDeclaration(bool InTemplateParameter) {
+if (!CurrentToken || CurrentToken->isNot(tok::less))
+  return false;
+
+InTemplateDeclaration = true;
+CurrentToken->setType(TT_TemplateOpener);
+next();
+
+const bool WellFormed = parseAngle();
+InTemplateDeclaration = InTemplateParameter;
+
+if (!WellFormed)
+  return false;
+
+if (CurrentToken && !InTemplateParameter)
+  CurrentToken->Previous->ClosesTemplateDeclaration = true;
+
+return true;
   }
```

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


[clang] [clang-format] Fix a bug in annotating lambda l_square (PR #95084)

2024-06-12 Thread Owen Pan via cfe-commits

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


[clang] [clang-format] Fix a bug in annotating lambda l_square (PR #95084)

2024-06-11 Thread Owen Pan via cfe-commits


@@ -1591,6 +1591,12 @@ TEST_F(TokenAnnotatorTest, UnderstandsLambdas) {
   EXPECT_TOKEN(Tokens[15], tok::arrow, TT_TrailingReturnArrow);
   EXPECT_TOKEN(Tokens[17], tok::l_brace, TT_LambdaLBrace);
 
+  Tokens = annotate("auto l = [] -> struct S { return {}; };");

owenca wrote:

Not really. I removed the assignment.

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


[clang] [clang-format] Fix a bug in annotating lambda l_square (PR #95084)

2024-06-11 Thread Owen Pan via cfe-commits

https://github.com/owenca updated 
https://github.com/llvm/llvm-project/pull/95084

>From b89f8a5bcbf525d779565219951359162655929e Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Tue, 11 Jun 2024 01:32:32 -0700
Subject: [PATCH 1/2] [clang-format] Fix a bug in annotating lambda l_square

Fixes #95072.
---
 clang/lib/Format/UnwrappedLineParser.cpp  | 2 ++
 clang/unittests/Format/TokenAnnotatorTest.cpp | 6 ++
 2 files changed, 8 insertions(+)

diff --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index eb96b54ec4c96..08387d2e08ee0 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -2257,6 +2257,8 @@ bool UnwrappedLineParser::tryToParseLambda() {
   break;
 case tok::kw_auto:
 case tok::kw_class:
+case tok::kw_struct:
+case tok::kw_union:
 case tok::kw_template:
 case tok::kw_typename:
 case tok::amp:
diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 3d609a1f041bc..0a1fb8c657ceb 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -1591,6 +1591,12 @@ TEST_F(TokenAnnotatorTest, UnderstandsLambdas) {
   EXPECT_TOKEN(Tokens[15], tok::arrow, TT_TrailingReturnArrow);
   EXPECT_TOKEN(Tokens[17], tok::l_brace, TT_LambdaLBrace);
 
+  Tokens = annotate("auto l = [] -> struct S { return {}; };");
+  ASSERT_EQ(Tokens.size(), 16u) << Tokens;
+  EXPECT_TOKEN(Tokens[3], tok::l_square, TT_LambdaLSquare);
+  EXPECT_TOKEN(Tokens[5], tok::arrow, TT_TrailingReturnArrow);
+  EXPECT_TOKEN(Tokens[8], tok::l_brace, TT_LambdaLBrace);
+
   Tokens = annotate("[]  () {}");
   ASSERT_EQ(Tokens.size(), 11u) << Tokens;
   EXPECT_TOKEN(Tokens[0], tok::l_square, TT_LambdaLSquare);

>From 14cd4ea57ed78a5f08780882f5ec5d3d237b0316 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Tue, 11 Jun 2024 19:16:54 -0700
Subject: [PATCH 2/2] Simplify the test case.

---
 clang/unittests/Format/TokenAnnotatorTest.cpp | 12 ++--
 1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 0a1fb8c657ceb..27b903468de4b 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -1585,18 +1585,18 @@ TEST_F(TokenAnnotatorTest, UnderstandsLambdas) {
   EXPECT_TOKEN(Tokens[2], tok::arrow, TT_TrailingReturnArrow);
   EXPECT_TOKEN(Tokens[4], tok::l_brace, TT_LambdaLBrace);
 
+  Tokens = annotate("[] -> struct S { return {}; }");
+  ASSERT_EQ(Tokens.size(), 12u) << Tokens;
+  EXPECT_TOKEN(Tokens[0], tok::l_square, TT_LambdaLSquare);
+  EXPECT_TOKEN(Tokens[2], tok::arrow, TT_TrailingReturnArrow);
+  EXPECT_TOKEN(Tokens[5], tok::l_brace, TT_LambdaLBrace);
+
   Tokens = annotate("foo([&](u32 bar) __attribute__((attr)) -> void {});");
   ASSERT_EQ(Tokens.size(), 22u) << Tokens;
   EXPECT_TOKEN(Tokens[2], tok::l_square, TT_LambdaLSquare);
   EXPECT_TOKEN(Tokens[15], tok::arrow, TT_TrailingReturnArrow);
   EXPECT_TOKEN(Tokens[17], tok::l_brace, TT_LambdaLBrace);
 
-  Tokens = annotate("auto l = [] -> struct S { return {}; };");
-  ASSERT_EQ(Tokens.size(), 16u) << Tokens;
-  EXPECT_TOKEN(Tokens[3], tok::l_square, TT_LambdaLSquare);
-  EXPECT_TOKEN(Tokens[5], tok::arrow, TT_TrailingReturnArrow);
-  EXPECT_TOKEN(Tokens[8], tok::l_brace, TT_LambdaLBrace);
-
   Tokens = annotate("[]  () {}");
   ASSERT_EQ(Tokens.size(), 11u) << Tokens;
   EXPECT_TOKEN(Tokens[0], tok::l_square, TT_LambdaLSquare);

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


[clang] [clang-format] Don't count template template parameter as declaration (PR #95025)

2024-06-11 Thread Owen Pan via cfe-commits

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


[clang] [clang-format] Don't count template template parameter as declaration (PR #95025)

2024-06-11 Thread Owen Pan via cfe-commits


@@ -584,6 +584,23 @@ TEST_F(TokenAnnotatorTest, 
UnderstandsNonTemplateAngleBrackets) {
   EXPECT_TOKEN(Tokens[20], tok::greater, TT_BinaryOperator);
 }
 
+TEST_F(TokenAnnotatorTest, UnderstandsTemplateTemplateParameters) {
+  auto Tokens = annotate("template  typename X,\n"
+ "  template  typename Y,\n"
+ "  typename... T>\n"
+ "class A {};");
+  ASSERT_EQ(Tokens.size(), 28u) << Tokens;
+  EXPECT_TOKEN(Tokens[1], tok::less, TT_TemplateOpener);
+  EXPECT_TOKEN(Tokens[3], tok::less, TT_TemplateOpener);
+  EXPECT_TOKEN(Tokens[6], tok::greater, TT_TemplateCloser);
+  EXPECT_EQ(Tokens[6]->ClosesTemplateDeclaration, 0u);
+  EXPECT_TOKEN(Tokens[11], tok::less, TT_TemplateOpener);
+  EXPECT_TOKEN(Tokens[14], tok::greater, TT_TemplateCloser);
+  EXPECT_EQ(Tokens[14]->ClosesTemplateDeclaration, 0u);
+  EXPECT_TOKEN(Tokens[21], tok::greater, TT_TemplateCloser);
+  EXPECT_EQ(Tokens[21]->ClosesTemplateDeclaration, 1u);

owenca wrote:

```suggestion
  EXPECT_TRUE(Tokens[21]->ClosesTemplateDeclaration);
```

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


[clang] [clang-format] Don't count template template parameter as declaration (PR #95025)

2024-06-11 Thread Owen Pan via cfe-commits


@@ -584,6 +584,23 @@ TEST_F(TokenAnnotatorTest, 
UnderstandsNonTemplateAngleBrackets) {
   EXPECT_TOKEN(Tokens[20], tok::greater, TT_BinaryOperator);
 }
 
+TEST_F(TokenAnnotatorTest, UnderstandsTemplateTemplateParameters) {
+  auto Tokens = annotate("template  typename X,\n"
+ "  template  typename Y,\n"
+ "  typename... T>\n"
+ "class A {};");
+  ASSERT_EQ(Tokens.size(), 28u) << Tokens;
+  EXPECT_TOKEN(Tokens[1], tok::less, TT_TemplateOpener);
+  EXPECT_TOKEN(Tokens[3], tok::less, TT_TemplateOpener);
+  EXPECT_TOKEN(Tokens[6], tok::greater, TT_TemplateCloser);
+  EXPECT_EQ(Tokens[6]->ClosesTemplateDeclaration, 0u);
+  EXPECT_TOKEN(Tokens[11], tok::less, TT_TemplateOpener);
+  EXPECT_TOKEN(Tokens[14], tok::greater, TT_TemplateCloser);
+  EXPECT_EQ(Tokens[14]->ClosesTemplateDeclaration, 0u);

owenca wrote:

Ditto.

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


[clang] [clang-format] Don't count template template parameter as declaration (PR #95025)

2024-06-11 Thread Owen Pan via cfe-commits


@@ -584,6 +584,23 @@ TEST_F(TokenAnnotatorTest, 
UnderstandsNonTemplateAngleBrackets) {
   EXPECT_TOKEN(Tokens[20], tok::greater, TT_BinaryOperator);
 }
 
+TEST_F(TokenAnnotatorTest, UnderstandsTemplateTemplateParameters) {
+  auto Tokens = annotate("template  typename X,\n"
+ "  template  typename Y,\n"
+ "  typename... T>\n"
+ "class A {};");
+  ASSERT_EQ(Tokens.size(), 28u) << Tokens;
+  EXPECT_TOKEN(Tokens[1], tok::less, TT_TemplateOpener);
+  EXPECT_TOKEN(Tokens[3], tok::less, TT_TemplateOpener);
+  EXPECT_TOKEN(Tokens[6], tok::greater, TT_TemplateCloser);
+  EXPECT_EQ(Tokens[6]->ClosesTemplateDeclaration, 0u);

owenca wrote:

```suggestion
  EXPECT_FALSE(Tokens[6]->ClosesTemplateDeclaration);
```

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


[clang] [clang-format] Don't count template template parameter as declaration (PR #95025)

2024-06-11 Thread Owen Pan via cfe-commits


@@ -1269,10 +1269,17 @@ class AnnotatingParser {
 if (CurrentToken && CurrentToken->is(tok::less)) {
   CurrentToken->setType(TT_TemplateOpener);
   next();
-  if (!parseAngle())
+  TemplateDeclarationDepth++;
+  if (!parseAngle()) {
+TemplateDeclarationDepth--;
 return false;
-  if (CurrentToken)
+  }
+  TemplateDeclarationDepth--;
+  if (CurrentToken &&
+  (TemplateDeclarationDepth == 0 ||
+   !CurrentToken->isOneOf(tok::kw_typename, tok::kw_class))) {

owenca wrote:

Maybe something like the following?
```
-  bool parseTemplateDeclaration() {
+  bool parseTemplateDeclaration(bool InTemplateParameter) {
 if (CurrentToken && CurrentToken->is(tok::less)) {
   CurrentToken->setType(TT_TemplateOpener);
+  InTemplateDeclaration = true;
   next();
   if (!parseAngle())
 return false;
-  if (CurrentToken)
-CurrentToken->Previous->ClosesTemplateDeclaration = true;
+  if (!InTemplateParameter) {
+InTemplateDeclaration = false;
+if (CurrentToken)
+  CurrentToken->Previous->ClosesTemplateDeclaration = true;
+  }
   return true;
 }
```
And call it in `consumeToken()` like this:
```
 case tok::kw_template:
-  parseTemplateDeclaration();
+  parseTemplateDeclaration(InTemplateDeclaration);
   break;
```

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


[clang] [clang-format] Don't count template template parameter as declaration (PR #95025)

2024-06-11 Thread Owen Pan via cfe-commits


@@ -1269,10 +1269,17 @@ class AnnotatingParser {
 if (CurrentToken && CurrentToken->is(tok::less)) {
   CurrentToken->setType(TT_TemplateOpener);
   next();
-  if (!parseAngle())
+  TemplateDeclarationDepth++;
+  if (!parseAngle()) {
+TemplateDeclarationDepth--;
 return false;
-  if (CurrentToken)
+  }
+  TemplateDeclarationDepth--;
+  if (CurrentToken &&
+  !(TemplateDeclarationDepth > 0 &&
+CurrentToken->isOneOf(tok::kw_typename, tok::kw_class))) {

owenca wrote:

Maybe something like the following:
```
-  bool parseTemplateDeclaration() {
+  bool parseTemplateDeclaration(bool IsParameter) {
 if (CurrentToken && CurrentToken->is(tok::less)) {
   CurrentToken->setType(TT_TemplateOpener);
+  InTemplateDeclaration = true;
   next();
   if (!parseAngle())
 return false;
-  if (CurrentToken)
-CurrentToken->Previous->ClosesTemplateDeclaration = true;
+  if (!IsParameter) {
+InTemplateDeclaration = false;
+if (CurrentToken)
+  CurrentToken->Previous->ClosesTemplateDeclaration = true;
+  }
```
And call the function in `consumeToken()` like this:
```
 case tok::kw_template:
-  parseTemplateDeclaration();
+  parseTemplateDeclaration(InTemplateDeclaration);
   break;
```

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


[clang] [clang-format] Don't count template template parameter as declaration (PR #95025)

2024-06-11 Thread Owen Pan via cfe-commits


@@ -127,7 +127,7 @@ class AnnotatingParser {
SmallVector )
   : Style(Style), Line(Line), CurrentToken(Line.First), AutoFound(false),
 IsCpp(Style.isCpp()), LangOpts(getFormattingLangOpts(Style)),
-Keywords(Keywords), Scopes(Scopes) {
+Keywords(Keywords), Scopes(Scopes), TemplateDeclarationDepth(0) {

owenca wrote:

```suggestion
Keywords(Keywords), Scopes(Scopes), InTemplateDeclaration(false) {
```

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


[clang] [clang-format] Don't count template template parameter as declaration (PR #95025)

2024-06-11 Thread Owen Pan via cfe-commits


@@ -584,6 +584,23 @@ TEST_F(TokenAnnotatorTest, 
UnderstandsNonTemplateAngleBrackets) {
   EXPECT_TOKEN(Tokens[20], tok::greater, TT_BinaryOperator);
 }
 
+TEST_F(TokenAnnotatorTest, UnderstandsTemplateTemplateParameters) {
+  auto Tokens = annotate("template  typename X,\n"
+ "  template  typename Y,\n"

owenca wrote:

```suggestion
 "  template  class Y,\n"
```
To cover both type-parameter keys.

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


[clang] [clang-format] Add DiagHandler for getStyle function (PR #91317)

2024-06-11 Thread Owen Pan via cfe-commits

owenca wrote:

@mydeveloperday requested it. See 
https://github.com/llvm/llvm-project/pull/91317#pullrequestreview-2095010527.

There are calls to `getStyle()` in `ConfigParseTest.cpp`. Maybe add a test 
there?

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


[clang] [clang-format] Add DiagHandler for getStyle function (PR #91317)

2024-06-11 Thread Owen Pan via cfe-commits

owenca wrote:

> Am I right that no one has a major issue with the patch? So fixing the 
> "const" issue and adding a unit test will let that in?

Can you add a unit test?

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


[clang] [clang-format] Fix a bug in annotating lambda l_square (PR #95084)

2024-06-11 Thread Owen Pan via cfe-commits

https://github.com/owenca created 
https://github.com/llvm/llvm-project/pull/95084

Fixes #95072.

>From b89f8a5bcbf525d779565219951359162655929e Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Tue, 11 Jun 2024 01:32:32 -0700
Subject: [PATCH] [clang-format] Fix a bug in annotating lambda l_square

Fixes #95072.
---
 clang/lib/Format/UnwrappedLineParser.cpp  | 2 ++
 clang/unittests/Format/TokenAnnotatorTest.cpp | 6 ++
 2 files changed, 8 insertions(+)

diff --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index eb96b54ec4c96..08387d2e08ee0 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -2257,6 +2257,8 @@ bool UnwrappedLineParser::tryToParseLambda() {
   break;
 case tok::kw_auto:
 case tok::kw_class:
+case tok::kw_struct:
+case tok::kw_union:
 case tok::kw_template:
 case tok::kw_typename:
 case tok::amp:
diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 3d609a1f041bc..0a1fb8c657ceb 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -1591,6 +1591,12 @@ TEST_F(TokenAnnotatorTest, UnderstandsLambdas) {
   EXPECT_TOKEN(Tokens[15], tok::arrow, TT_TrailingReturnArrow);
   EXPECT_TOKEN(Tokens[17], tok::l_brace, TT_LambdaLBrace);
 
+  Tokens = annotate("auto l = [] -> struct S { return {}; };");
+  ASSERT_EQ(Tokens.size(), 16u) << Tokens;
+  EXPECT_TOKEN(Tokens[3], tok::l_square, TT_LambdaLSquare);
+  EXPECT_TOKEN(Tokens[5], tok::arrow, TT_TrailingReturnArrow);
+  EXPECT_TOKEN(Tokens[8], tok::l_brace, TT_LambdaLBrace);
+
   Tokens = annotate("[]  () {}");
   ASSERT_EQ(Tokens.size(), 11u) << Tokens;
   EXPECT_TOKEN(Tokens[0], tok::l_square, TT_LambdaLSquare);

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


[clang] [clang-format] Fix a bug in indenting lambda trailing arrows (PR #94560)

2024-06-10 Thread Owen Pan via cfe-commits

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


[clang] [clang-format] Fix a bug in indenting lambda trailing arrows (PR #94560)

2024-06-10 Thread Owen Pan via cfe-commits

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


[clang] [clang-format] Fix a bug in indenting lambda trailing arrows (PR #94560)

2024-06-10 Thread Owen Pan via cfe-commits

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


[clang] [clang-format] fix incorrectly indents lambda trailing return (PR #94560)

2024-06-09 Thread Owen Pan via cfe-commits

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


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


[clang] [clang-format] add an option to insert a space only for non-code block empty braces, not for empty parentheses (PR #93634)

2024-06-09 Thread Owen Pan via cfe-commits

owenca wrote:

> See [#93635 
> (comment)](https://github.com/llvm/llvm-project/issues/93635#issuecomment-2138778128).

@khei4 maybe an `enum` for `SpaceInEmptyBraces` with `Always`, `Never`, and 
`Custom`. (IMO `Leave` doesn't make sense.)

With `Custom`, a list of boolean suboptions e.g. `Function`, `List`, etc. can 
be set individually.

We have the following brace types now:
```
BlockLBrace
BracedListLBrace
ClassLBrace
ControlStatementLBrace
ElseLBrace
EnumLBrace
FunctionLBrace
InlineASMBrace
LambdaLBrace
NamespaceLBrace
ObjCBlockLBrace
RecordLBrace
RequiresExpressionLBrace
StructLBrace
SwitchExpressionLBrace
UnionLBrace
```
I would implement all that make sense or are applicable to WebKit.


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


[clang] [clang-format] add an option to insert a space only for non-code block empty braces, not for empty parentheses (PR #93634)

2024-06-09 Thread Owen Pan via cfe-commits


@@ -1864,7 +1894,11 @@ FormatStyle getWebKitStyle() {
   Style.ObjCSpaceAfterProperty = true;
   Style.PointerAlignment = FormatStyle::PAS_Left;
   Style.SpaceBeforeCpp11BracedList = true;
-  Style.SpaceInEmptyBlock = true;
+  Style.SpaceInEmptyBraces = FormatStyle::SIEBO_Custom;
+  Style.SpaceInEmptyBracesOptions.Block = true;
+  Style.SpaceInEmptyBracesOptions.InitList = true;
+  Style.SpacesInParensOptions.InEmptyParentheses = false;

owenca wrote:

IMO we need to go by the published [WebKit coding 
style](https://webkit.org/code-style-guidelines/), not the script.

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


[clang] [clang-format] fix incorrectly indents lambda trailing return (PR #94560)

2024-06-09 Thread Owen Pan via cfe-commits

owenca wrote:

> Technically also applies to attributes applied to the return type of the 
> lambda, i.e.
> 
> ```
> int main() {
>   very_long_function_name_yes_it_is_really_long(
>   // also happens with constexpr specifier
>   [](auto n) [[attribute]]
>   -> std::enable_if_t<
>   std::is_arithmetic::value &&
>   !std::is_same, bool>::value> {
> do_something(n * 2);
>   });
> }
> ```
> 
> ...but currently at least no valid C++ attribute can go in that spot

We can easily take care of it though. See 
https://github.com/llvm/llvm-project/pull/94560#discussion_r1632406068.

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


[clang] [clang-format] fix incorrectly indents lambda trailing return (PR #94560)

2024-06-09 Thread Owen Pan via cfe-commits


@@ -22858,6 +22858,36 @@ TEST_F(FormatTest, FormatsLambdas) {
   "  //\n"
   "});");
 
+  FormatStyle LLVMStyle = getLLVMStyleWithColumns(60);
+
+  verifyFormat("int main() {\n"
+   "  very_long_function_name_yes_it_is_really_long(\n"
+   "  [](auto n)\n"
+   "  -> std::unordered_map {\n"
+   "really_do_something();\n"
+   "  });\n"
+   "}",
+   LLVMStyle);
+  verifyFormat("int main() {\n"
+   "  very_long_function_name_yes_it_is_really_long(\n"
+   "  [](auto n) noexcept\n"
+   "  -> std::unordered_map {\n"
+   "really_do_something();\n"
+   "  });\n"
+   "}",
+   LLVMStyle);

owenca wrote:

```suggestion
  verifyFormat("very_long_function_name_yes_it_is_really_long(\n"
   "[](auto n) noexcept [[back_attr]]\n"
   "-> std::unordered_map {\n"
   "  really_do_something();\n"
   "});",
   Style);
```
Removes `main()` and adds `[[back_attr]]`.

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


[clang] [clang-format] fix incorrectly indents lambda trailing return (PR #94560)

2024-06-09 Thread Owen Pan via cfe-commits


@@ -1457,6 +1457,11 @@ unsigned ContinuationIndenter::getNewLineColumn(const 
LineState ) {
   !Current.isOneOf(tok::colon, tok::comment)) {
 return ContinuationIndent;
   }
+  if (Current.is(TT_TrailingReturnArrow) &&
+  Previous.isOneOf(tok::kw_noexcept, tok::kw_mutable, tok::kw_constexpr,
+   tok::kw_consteval, tok::kw_static)) {

owenca wrote:

```suggestion
   tok::kw_consteval, tok::kw_static, TT_AttributeSquare)) {
```
And move this `if` block to line 1260.

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


[clang] [clang-format] fix incorrectly indents lambda trailing return (PR #94560)

2024-06-09 Thread Owen Pan via cfe-commits


@@ -22858,6 +22858,36 @@ TEST_F(FormatTest, FormatsLambdas) {
   "  //\n"
   "});");
 
+  FormatStyle LLVMStyle = getLLVMStyleWithColumns(60);
+
+  verifyFormat("int main() {\n"
+   "  very_long_function_name_yes_it_is_really_long(\n"
+   "  [](auto n)\n"
+   "  -> std::unordered_map {\n"
+   "really_do_something();\n"
+   "  });\n"
+   "}",
+   LLVMStyle);

owenca wrote:

We can drop this test.

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


[clang] [clang-format] fix incorrectly indents lambda trailing return (PR #94560)

2024-06-09 Thread Owen Pan via cfe-commits


@@ -22858,6 +22858,36 @@ TEST_F(FormatTest, FormatsLambdas) {
   "  //\n"
   "});");
 
+  FormatStyle LLVMStyle = getLLVMStyleWithColumns(60);
+
+  verifyFormat("int main() {\n"
+   "  very_long_function_name_yes_it_is_really_long(\n"
+   "  [](auto n)\n"
+   "  -> std::unordered_map {\n"
+   "really_do_something();\n"
+   "  });\n"
+   "}",
+   LLVMStyle);
+  verifyFormat("int main() {\n"
+   "  very_long_function_name_yes_it_is_really_long(\n"
+   "  [](auto n) noexcept\n"
+   "  -> std::unordered_map {\n"
+   "really_do_something();\n"
+   "  });\n"
+   "}",
+   LLVMStyle);
+  verifyFormat("int main() {\n"
+   "  very_long_function_name_yes_it_is_really_long(\n"
+   "  [](auto n) constexpr\n"
+   "  -> std::unordered_map {\n"
+   "really_do_something();\n"
+   "  });\n"
+   "}",
+   LLVMStyle);

owenca wrote:

Please remove `main()`.

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


[clang] [clang-format] Fix bad comment indentation before ifdef after braceless if (PR #94776)

2024-06-09 Thread Owen Pan via cfe-commits

owenca wrote:

This patch formats
```
void f() {
  if (foo)
bar(); // Comment
#if BAZ
  baz();
#endif
}
```
to
```
void f() {
  if (foo)
bar();
// Comment
#if BAZ
  baz();
#endif
}
```
The trailing comment shouldn't be wrapped.

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


[clang] [clang-format] Fix bad comment indentation before ifdef after braceless if (PR #94776)

2024-06-08 Thread Owen Pan via cfe-commits


@@ -796,6 +796,24 @@ TEST_F(FormatTestComments, 
ParsesCommentsAdjacentToPPDirectives) {
 format("namespace {}\n   /* Test */#define A"));
 }
 
+
+TEST_F(FormatTestComments, DeIdentsCommentBeforeIfdefAfterBracelessIf) {
+  EXPECT_EQ("void f() {\n"

owenca wrote:

You don't need to because the default style is `LLVM`.

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


[clang] [clang-format] Fix bad comment indentation before ifdef after braceless if (PR #94776)

2024-06-08 Thread Owen Pan via cfe-commits


@@ -338,6 +338,9 @@ class UnwrappedLineParser {
   // `decltype(auto)`.
   bool IsDecltypeAutoFunction = false;
 
+  // Current nesting depth within unbraced codeblocks.

owenca wrote:

```suggestion
  // Nesting depth of unbraced body of a control statement.
```

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


[clang] [clang-format] Fix bad comment indentation before ifdef after braceless if (PR #94776)

2024-06-08 Thread Owen Pan via cfe-commits


@@ -4811,8 +4813,11 @@ void UnwrappedLineParser::readToken(int LevelDifference) 
{
(!Style.isVerilog() ||
 Keywords.isVerilogPPDirective(*Tokens->peekNextToken())) &&
FirstNonCommentOnLine) {
-  distributeComments(Comments, FormatTok);
-  Comments.clear();
+
+  if (!UnbracedBodyDepth) {
+distributeComments(Comments, FormatTok);
+Comments.clear();
+  }

owenca wrote:

```suggestion
  if (UnbracedBodyDepth == 0) {
distributeComments(Comments, FormatTok);
Comments.clear();
  }

```

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


[clang] [clang-format] Fix bad comment indentation before ifdef after braceless if (PR #94776)

2024-06-08 Thread Owen Pan via cfe-commits

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


[clang] [clang-format] Fix bad comment indentation before ifdef after braceless if (PR #94776)

2024-06-08 Thread Owen Pan via cfe-commits


@@ -796,6 +796,44 @@ TEST_F(FormatTestComments, 
ParsesCommentsAdjacentToPPDirectives) {
 format("namespace {}\n   /* Test */#define A"));
 }
 
+TEST_F(FormatTestComments, DeIdentsCommentBeforeIfdefAfterBracelessIf) {
+  verifyFormat("void f() {\n"
+   "  if (true)\n"
+   "int i;\n"
+   "  /* comment */\n"
+   "#ifdef A\n"
+   "  int j;\n"
+   "#endif\n"
+   "}",
+   "void f() {\n"
+   "  if (true)\n"
+   "int i;\n"
+   "/* comment */\n"
+   "#ifdef A\n"
+   "  int j;\n"
+   "#endif\n"
+   "}");
+
+  verifyFormat("void f() {\n"
+   "  if (true)\n"
+   "int i;\n"
+   "  /* comment */\n"

owenca wrote:

It doesn't look right as the comment is likely for the line above it.

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


[clang] [clang-format] Fix bad comment indentation before ifdef after braceless if (PR #94776)

2024-06-08 Thread Owen Pan via cfe-commits


@@ -4828,7 +4833,10 @@ void UnwrappedLineParser::readToken(int LevelDifference) 
{
   PPBranchLevel > 0) {
 Line->Level += PPBranchLevel;
   }
-  flushComments(isOnNewLine(*FormatTok));
+
+  if (!UnbracedBodyDepth)

owenca wrote:

Ditto.

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


[clang] [clang-format] Fix bad comment indentation before ifdef after braceless if (PR #94776)

2024-06-08 Thread Owen Pan via cfe-commits

https://github.com/owenca commented:

What happens if the comment is unindented, with and without an empty line below 
it?

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


[clang] [clang-format]: Annotate colons found in inline assembly (PR #92617)

2024-06-06 Thread Owen Pan via cfe-commits

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


[clang] [clang-format][NFC] Remove an else after a return statement (PR #94548)

2024-06-06 Thread Owen Pan via cfe-commits

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


[clang] [clang-format] Fix a bug in `AlignAfterOpenBracket: DontAlign` (PR #94561)

2024-06-06 Thread Owen Pan via cfe-commits

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


[clang] [clang-format][NFC] Remove an else after a return statement (PR #94548)

2024-06-06 Thread Owen Pan via cfe-commits

owenca wrote:

It means "No Functional Change". See 
[here](https://llvm.org/docs/Lexicon.html#n).

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


[clang] [clang-format][NFC] Remove an else after a return statement (PR #94548)

2024-06-05 Thread Owen Pan via cfe-commits

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


[clang] [clang-format] remove redundant else statement (PR #94548)

2024-06-05 Thread Owen Pan via cfe-commits

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


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


[clang] [clang-format] Fix a bug in `AlignAfterOpenBracket: DontAlign` (PR #94561)

2024-06-05 Thread Owen Pan via cfe-commits

https://github.com/owenca created 
https://github.com/llvm/llvm-project/pull/94561

Fixes #94555.

>From f5a4cd0df1df390166adb8400e21894a0f2db18f Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Wed, 5 Jun 2024 19:18:19 -0700
Subject: [PATCH] [clang-format] Fix a bug in `AlignAfterOpenBracket:
 DontAlign`

Fixes #94555.
---
 clang/lib/Format/ContinuationIndenter.cpp | 2 +-
 clang/unittests/Format/FormatTest.cpp | 8 
 2 files changed, 9 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index 6b9fbfe0ebf53..be684ac71cd61 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -1712,7 +1712,7 @@ void 
ContinuationIndenter::moveStatePastFakeLParens(LineState ,
 (!Previous || Previous->isNot(tok::kw_return) ||
  (Style.Language != FormatStyle::LK_Java && PrecedenceLevel > 0)) &&
 (Style.AlignAfterOpenBracket != FormatStyle::BAS_DontAlign ||
- PrecedenceLevel != prec::Comma || Current.NestingLevel == 0) &&
+ PrecedenceLevel > prec::Comma || Current.NestingLevel == 0) &&
 (!Style.isTableGen() ||
  (Previous && Previous->isOneOf(TT_TableGenDAGArgListComma,
 TT_TableGenDAGArgListCommaToBreak {
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 4e427268fb82a..dbc1916825f33 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -9241,6 +9241,14 @@ TEST_F(FormatTest, AlignsAfterOpenBracket) {
"b));",
Style);
 
+  Style.ColumnLimit = 30;
+  verifyFormat("for (int foo = 0; foo < FOO;\n"
+   "++foo) {\n"
+   "  bar(foo);\n"
+   "}",
+   Style);
+  Style.ColumnLimit = 80;
+
   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
   Style.BinPackArguments = false;
   Style.BinPackParameters = false;

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


[clang] [clang-format] Don't format comments in SkipMacroDefinitionBody (PR #94425)

2024-06-05 Thread Owen Pan via cfe-commits

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


[clang] [clang-format] Don't format comments in SkipMacroDefinitionBody (PR #94425)

2024-06-04 Thread Owen Pan via cfe-commits

https://github.com/owenca created 
https://github.com/llvm/llvm-project/pull/94425

Fixes #94326.

>From 7e4c3e6b5b77085f795d6ccdfbf7279e32741b16 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Tue, 4 Jun 2024 21:10:14 -0700
Subject: [PATCH] [clang-format] Don't format comments in
 SkipMacroDefinitionBody

Fixes #94326.
---
 clang/lib/Format/UnwrappedLineParser.cpp |  6 +++---
 clang/unittests/Format/FormatTest.cpp| 11 ++-
 2 files changed, 13 insertions(+), 4 deletions(-)

diff --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index d6061c2666c2a..eb96b54ec4c96 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -1181,10 +1181,10 @@ void UnwrappedLineParser::parsePPDefine() {
   Line->InMacroBody = true;
 
   if (Style.SkipMacroDefinitionBody) {
-do {
+while (!eof()) {
   FormatTok->Finalized = true;
-  nextToken();
-} while (!eof());
+  FormatTok = Tokens->getNextToken();
+}
 addUnwrappedLine();
 return;
   }
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 004ecb63f6620..4e427268fb82a 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -24879,7 +24879,7 @@ TEST_F(FormatTest, SkipMacroDefinitionBody) {
Style);
 
   // With comments.
-  verifyFormat("/* */ #define A  a //  a  a", "/* */  # define A  a  //  a  a",
+  verifyFormat("/* */ #define A  a  //  a  a", "/* */  # define A  a  //  a  
a",
Style);
   verifyNoChange("/* */ #define A  a //  a  a", Style);
 
@@ -24891,6 +24891,15 @@ TEST_F(FormatTest, SkipMacroDefinitionBody) {
"int aaa; // a",
Style);
 
+  verifyNoChange(
+  "#define MACRO_WITH_COMMENTS()   
\\\n"
+  "  public:   
\\\n"
+  "/* Documentation parsed by Doxygen for the following method. */ 
\\\n"
+  "static MyType getClassTypeId(); 
\\\n"
+  "/** Normal comment for the following method. */ 
\\\n"
+  "virtual MyType getTypeId() const;",
+  Style);
+
   // multiline macro definitions
   verifyNoChange("#define A  a\\\n"
  "  A  a \\\n "

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


  1   2   3   4   5   6   7   8   9   10   >