r314279 - [clang-format] Fix FixNamespaceComments when BraceWrapping AfterNamespace is true.

2017-09-27 Thread Marek Kurdej via cfe-commits
Author: mkurdej
Date: Wed Sep 27 00:51:51 2017
New Revision: 314279

URL: http://llvm.org/viewvc/llvm-project?rev=314279&view=rev
Log:
[clang-format] Fix FixNamespaceComments when BraceWrapping AfterNamespace is 
true.

Summary:
NamespaceEndCommentsFixer did not fix namespace comments when the brace opening 
the namespace was not on the same line as the "namespace" keyword.
It occurs in Allman, GNU and Linux styles and whenever 
BraceWrapping.AfterNamespace is true.

Before:
```lang=cpp
namespace a
{
void f();
void g();
}
```

After:
```lang=cpp
namespace a
{
void f();
void g();
} // namespace a
```

Reviewers: krasimir

Reviewed By: krasimir

Subscribers: klimek, cfe-commits

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

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

Modified: cfe/trunk/lib/Format/NamespaceEndCommentsFixer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/NamespaceEndCommentsFixer.cpp?rev=314279&r1=314278&r2=314279&view=diff
==
--- cfe/trunk/lib/Format/NamespaceEndCommentsFixer.cpp (original)
+++ cfe/trunk/lib/Format/NamespaceEndCommentsFixer.cpp Wed Sep 27 00:51:51 2017
@@ -118,6 +118,12 @@ getNamespaceToken(const AnnotatedLine *l
 return nullptr;
   assert(StartLineIndex < AnnotatedLines.size());
   const FormatToken *NamespaceTok = AnnotatedLines[StartLineIndex]->First;
+  if (NamespaceTok->is(tok::l_brace)) {
+// "namespace" keyword can be on the line preceding '{', e.g. in styles
+// where BraceWrapping.AfterNamespace is true.
+if (StartLineIndex > 0)
+  NamespaceTok = AnnotatedLines[StartLineIndex - 1]->First;
+  }
   // Detect "(inline)? namespace" in the beginning of a line.
   if (NamespaceTok->is(tok::kw_inline))
 NamespaceTok = NamespaceTok->getNextNonComment();

Modified: cfe/trunk/unittests/Format/FormatTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTest.cpp?rev=314279&r1=314278&r2=314279&view=diff
==
--- cfe/trunk/unittests/Format/FormatTest.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTest.cpp Wed Sep 27 00:51:51 2017
@@ -1413,7 +1413,7 @@ TEST_F(FormatTest, FormatsTypedefEnum) {
   verifyFormat("typedef enum {} EmptyEnum;");
   verifyFormat("typedef enum { A, B, C } ShortEnum;");
   verifyFormat("typedef enum {\n"
-   "  ZERO = 0,\n" 
+   "  ZERO = 0,\n"
"  ONE = 1,\n"
"  TWO = 2,\n"
"  THREE = 3\n"
@@ -1425,7 +1425,7 @@ TEST_F(FormatTest, FormatsTypedefEnum) {
   verifyFormat("typedef enum { A, B, C } ShortEnum;");
   verifyFormat("typedef enum\n"
"{\n"
-   "  ZERO = 0,\n" 
+   "  ZERO = 0,\n"
"  ONE = 1,\n"
"  TWO = 2,\n"
"  THREE = 3\n"
@@ -9323,7 +9323,7 @@ TEST_F(FormatTest, LinuxBraceBreaking) {
"struct B {\n"
"  int x;\n"
"};\n"
-   "}\n",
+   "} // namespace a\n",
LinuxBraceStyle);
   verifyFormat("enum X {\n"
"  Y = 0,\n"
@@ -9453,6 +9453,19 @@ TEST_F(FormatTest, StroustrupBraceBreaki
 TEST_F(FormatTest, AllmanBraceBreaking) {
   FormatStyle AllmanBraceStyle = getLLVMStyle();
   AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman;
+
+  EXPECT_EQ("namespace a\n"
+"{\n"
+"void f();\n"
+"void g();\n"
+"} // namespace a\n",
+format("namespace a\n"
+   "{\n"
+   "void f();\n"
+   "void g();\n"
+   "}\n",
+   AllmanBraceStyle));
+
   verifyFormat("namespace a\n"
"{\n"
"class A\n"
@@ -9471,7 +9484,7 @@ TEST_F(FormatTest, AllmanBraceBreaking)
"{\n"
"  int x;\n"
"};\n"
-   "}",
+   "} // namespace a",
AllmanBraceStyle);
 
   verifyFormat("void f()\n"
@@ -9677,7 +9690,7 @@ TEST_F(FormatTest, GNUBraceBreaking) {
"  }\n"
"  void g() { return; }\n"
"}\n"
-   "}",
+   "} // namespace a",
GNUBraceStyle);
 
   verifyFormat("void f()\n"


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


[clang-tools-extra] r344785 - [clang-tidy] Resolve readability-else-after-return false positive for constexpr if.

2018-10-19 Thread Marek Kurdej via cfe-commits
Author: mkurdej
Date: Fri Oct 19 08:26:17 2018
New Revision: 344785

URL: http://llvm.org/viewvc/llvm-project?rev=344785&view=rev
Log:
[clang-tidy] Resolve readability-else-after-return false positive for constexpr 
if.

Summary:
It fixes the false positive when using constexpr if and where else cannot be 
removed:

Example:
```
  if constexpr (sizeof(int) > 4)
// ...
return /* ... */;
  else // This else cannot be removed.
// ...
return /* ... */;
```

Reviewers: alexfh, aaron.ballman

Reviewed By: aaron.ballman

Subscribers: lebedev.ri, xazax.hun, cfe-commits

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

Added:

clang-tools-extra/trunk/test/clang-tidy/readability-else-after-return-if-constexpr.cpp
Modified:
clang-tools-extra/trunk/clang-tidy/readability/ElseAfterReturnCheck.cpp

Modified: 
clang-tools-extra/trunk/clang-tidy/readability/ElseAfterReturnCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/readability/ElseAfterReturnCheck.cpp?rev=344785&r1=344784&r2=344785&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/readability/ElseAfterReturnCheck.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/readability/ElseAfterReturnCheck.cpp Fri 
Oct 19 08:26:17 2018
@@ -1,57 +1,58 @@
-//===--- ElseAfterReturnCheck.cpp - 
clang-tidy-===//
-//
-// The LLVM Compiler Infrastructure
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===--===//
-
-#include "ElseAfterReturnCheck.h"
-#include "clang/AST/ASTContext.h"
-#include "clang/ASTMatchers/ASTMatchFinder.h"
-#include "clang/Tooling/FixIt.h"
-
-using namespace clang::ast_matchers;
-
-namespace clang {
-namespace tidy {
-namespace readability {
-
-void ElseAfterReturnCheck::registerMatchers(MatchFinder *Finder) {
-  const auto ControlFlowInterruptorMatcher =
-  stmt(anyOf(returnStmt().bind("return"), continueStmt().bind("continue"),
- breakStmt().bind("break"),
- expr(ignoringImplicit(cxxThrowExpr().bind("throw");
-  Finder->addMatcher(
-  compoundStmt(forEach(
-  ifStmt(hasThen(stmt(
- anyOf(ControlFlowInterruptorMatcher,
-   compoundStmt(has(ControlFlowInterruptorMatcher),
- hasElse(stmt().bind("else")))
-  .bind("if"))),
-  this);
-}
-
-void ElseAfterReturnCheck::check(const MatchFinder::MatchResult &Result) {
-  const auto *If = Result.Nodes.getNodeAs("if");
-  SourceLocation ElseLoc = If->getElseLoc();
-  std::string ControlFlowInterruptor;
-  for (const auto *BindingName : {"return", "continue", "break", "throw"})
-if (Result.Nodes.getNodeAs(BindingName))
-  ControlFlowInterruptor = BindingName;
-
-  DiagnosticBuilder Diag = diag(ElseLoc, "do not use 'else' after '%0'")
-   << ControlFlowInterruptor;
-  Diag << tooling::fixit::createRemoval(ElseLoc);
-
-  // FIXME: Removing the braces isn't always safe. Do a more careful analysis.
-  // FIXME: Change clang-format to correctly un-indent the code.
-  if (const auto *CS = Result.Nodes.getNodeAs("else"))
-Diag << tooling::fixit::createRemoval(CS->getLBracLoc())
- << tooling::fixit::createRemoval(CS->getRBracLoc());
-}
-
-} // namespace readability
-} // namespace tidy
-} // namespace clang
+//===--- ElseAfterReturnCheck.cpp - 
clang-tidy-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===--===//
+
+#include "ElseAfterReturnCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Tooling/FixIt.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang {
+namespace tidy {
+namespace readability {
+
+void ElseAfterReturnCheck::registerMatchers(MatchFinder *Finder) {
+  const auto ControlFlowInterruptorMatcher =
+  stmt(anyOf(returnStmt().bind("return"), continueStmt().bind("continue"),
+ breakStmt().bind("break"),
+ expr(ignoringImplicit(cxxThrowExpr().bind("throw");
+  Finder->addMatcher(
+  compoundStmt(forEach(
+  ifStmt(unless(isConstexpr()),
+ hasThen(stmt(
+ anyOf(ControlFlowInterruptorMatcher,
+   compoundStmt(has(ControlFlowInterruptorMatcher),
+ hasElse(stmt().bind("else")))
+  .bind("if"))),
+  this);
+}
+
+void ElseAfterReturnCheck::check(const MatchFinder::MatchResult &Result) {
+  const auto *If = Result.Nodes.getNodeAs("if");
+  SourceLocation ElseLoc = I

r312723 - [clang-format] Add support for C++17 structured bindings.

2017-09-07 Thread Marek Kurdej via cfe-commits
Author: mkurdej
Date: Thu Sep  7 07:28:32 2017
New Revision: 312723

URL: http://llvm.org/viewvc/llvm-project?rev=312723&view=rev
Log:
[clang-format] Add support for C++17 structured bindings.

Summary:
Before:
```
auto[a, b] = f();
```

After:
```
auto [a, b] = f();
```
or, if SpacesInSquareBrackets is true:
```
auto [ a, b ] = f();
```

Reviewers: djasper

Reviewed By: djasper

Subscribers: cfe-commits, klimek

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

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

Modified: cfe/trunk/lib/Format/FormatToken.h
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/FormatToken.h?rev=312723&r1=312722&r2=312723&view=diff
==
--- cfe/trunk/lib/Format/FormatToken.h (original)
+++ cfe/trunk/lib/Format/FormatToken.h Thu Sep  7 07:28:32 2017
@@ -84,6 +84,7 @@ namespace format {
   TYPE(RegexLiteral) \
   TYPE(SelectorName) \
   TYPE(StartOfName) \
+  TYPE(StructuredBindingLSquare) \
   TYPE(TemplateCloser) \
   TYPE(TemplateOpener) \
   TYPE(TemplateString) \

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=312723&r1=312722&r2=312723&view=diff
==
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Thu Sep  7 07:28:32 2017
@@ -310,6 +310,16 @@ private:
 return false;
   }
 
+  bool isCppStructuredBinding(const FormatToken *Tok) {
+if (!Style.isCpp() || !Tok->is(tok::l_square))
+  return false;
+do {
+  Tok = Tok->getPreviousNonComment();
+} while (Tok && Tok->isOneOf(tok::kw_const, tok::kw_volatile, tok::amp,
+ tok::ampamp));
+return Tok && Tok->is(tok::kw_auto);
+  }
+
   bool parseSquare() {
 if (!CurrentToken)
   return false;
@@ -344,7 +354,9 @@ private:
 
 unsigned BindingIncrease = 1;
 if (Left->is(TT_Unknown)) {
-  if (StartsObjCMethodExpr) {
+  if (isCppStructuredBinding(Left)) {
+Left->Type = TT_StructuredBindingLSquare;
+  } else if (StartsObjCMethodExpr) {
 Left->Type = TT_ObjCMethodExpr;
   } else if (Style.Language == FormatStyle::LK_JavaScript && Parent &&
  Contexts.back().ContextKind == tok::l_brace &&
@@ -2261,17 +2273,20 @@ bool TokenAnnotator::spaceRequiredBetwee
   if (Left.is(tok::l_square))
 return (Left.is(TT_ArrayInitializerLSquare) &&
 Style.SpacesInContainerLiterals && Right.isNot(tok::r_square)) ||
-   (Left.is(TT_ArraySubscriptLSquare) && Style.SpacesInSquareBrackets 
&&
-Right.isNot(tok::r_square));
+   (Left.isOneOf(TT_ArraySubscriptLSquare,
+ TT_StructuredBindingLSquare) &&
+Style.SpacesInSquareBrackets && Right.isNot(tok::r_square));
   if (Right.is(tok::r_square))
 return Right.MatchingParen &&
((Style.SpacesInContainerLiterals &&
  Right.MatchingParen->is(TT_ArrayInitializerLSquare)) ||
 (Style.SpacesInSquareBrackets &&
- Right.MatchingParen->is(TT_ArraySubscriptLSquare)));
+ Right.MatchingParen->isOneOf(TT_ArraySubscriptLSquare,
+  TT_StructuredBindingLSquare)));
   if (Right.is(tok::l_square) &&
   !Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,
- TT_DesignatedInitializerLSquare) &&
+ TT_DesignatedInitializerLSquare,
+ TT_StructuredBindingLSquare) &&
   !Left.isOneOf(tok::numeric_constant, TT_DictLiteral))
 return false;
   if (Left.is(tok::l_brace) && Right.is(tok::r_brace))

Modified: cfe/trunk/unittests/Format/FormatTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTest.cpp?rev=312723&r1=312722&r2=312723&view=diff
==
--- cfe/trunk/unittests/Format/FormatTest.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTest.cpp Thu Sep  7 07:28:32 2017
@@ -11452,6 +11452,31 @@ TEST_F(FormatTest, DoNotFormatLikelyXml)
 format(" ", getGoogleStyle()));
 }
 
+TEST_F(FormatTest, StructuredBindings) {
+  // Structured bindings is a C++17 feature.
+  // all modes, including C++11, C++14 and C++17
+  verifyFormat("auto [a, b] = f();");
+  EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();"));
+  EXPECT_EQ("const auto [a, b] = f();", format("const   auto[a, b] = f();"));
+  EXPECT_EQ("auto const [a, b] = f();", format("auto  const[a, b] = f();"));
+  EXPECT_EQ("auto const volatile [a, b] = f();",
+format("auto  const   volatile[a, b] = f();"));
+  EXPECT_EQ("auto [a, b, c] = f();", format("auto   [  a  ,  b,c   ] = f();"));
+  EXPECT_EQ("aut

[clang-tools-extra] 340d111 - [clang-tidy] [doc] Fix hicpp-noexcept-move alias links.

2020-04-09 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2020-04-09T10:48:08+02:00
New Revision: 340d1119eddaa30446853832c3ad1e95c6ff96dc

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

LOG: [clang-tidy] [doc] Fix hicpp-noexcept-move alias links.

Added: 


Modified: 
clang-tools-extra/docs/clang-tidy/checks/hicpp-noexcept-move.rst
clang-tools-extra/docs/clang-tidy/checks/list.rst

Removed: 




diff  --git a/clang-tools-extra/docs/clang-tidy/checks/hicpp-noexcept-move.rst 
b/clang-tools-extra/docs/clang-tidy/checks/hicpp-noexcept-move.rst
index 10573eca7fc0..d96be9f8446e 100644
--- a/clang-tools-extra/docs/clang-tidy/checks/hicpp-noexcept-move.rst
+++ b/clang-tools-extra/docs/clang-tidy/checks/hicpp-noexcept-move.rst
@@ -1,9 +1,9 @@
 .. title:: clang-tidy - hicpp-noexcept-move
 .. meta::
-   :http-equiv=refresh: 5;URL=misc-noexcept-moveconstructor.html
+   :http-equiv=refresh: 5;URL=performance-noexcept-move-constructor.html
 
 hicpp-noexcept-move
 ===
 
-This check is an alias for `misc-noexcept-moveconstructor 
`_.
+This check is an alias for `performance-noexcept-move-constructor 
`_.
 Checks `rule 12.5.4 
`_
 to mark move assignment and move construction `noexcept`.

diff  --git a/clang-tools-extra/docs/clang-tidy/checks/list.rst 
b/clang-tools-extra/docs/clang-tidy/checks/list.rst
index 28a98e828ca0..768e10ef714f 100644
--- a/clang-tools-extra/docs/clang-tidy/checks/list.rst
+++ b/clang-tools-extra/docs/clang-tidy/checks/list.rst
@@ -404,7 +404,7 @@ Clang-Tidy Checks
`hicpp-new-delete-operators `_, 
`misc-new-delete-overloads `_,
`hicpp-no-array-decay `_, 
`cppcoreguidelines-pro-bounds-array-to-pointer-decay 
`_,
`hicpp-no-malloc `_, `cppcoreguidelines-no-malloc 
`_,
-   `hicpp-noexcept-move `_, 
`misc-noexcept-moveconstructor `_,
+   `hicpp-noexcept-move `_, 
`performance-noexcept-move-constructor 
`_,
`hicpp-special-member-functions `_, 
`cppcoreguidelines-special-member-functions 
`_,
`hicpp-static-assert `_, `misc-static-assert 
`_, "Yes"
`hicpp-undelegated-constructor `_, 
`bugprone-undelegated-constructor `_,



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


[clang] b18c63e - [clang-format] use spaces for alignment of binary/ternary expressions with UT_AlignWithSpaces

2020-08-11 Thread Marek Kurdej via cfe-commits

Author: Maximilian Fickert
Date: 2020-08-11T14:56:26+02:00
New Revision: b18c63e85aa8191e583cd1014757904c344b45d7

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

LOG: [clang-format] use spaces for alignment of binary/ternary expressions with 
UT_AlignWithSpaces

Use spaces to align binary and ternary expressions when using AlignOperands and 
UT_AlignWithSpaces.

This fixes an oversight in the new UT_AlignWithSpaces option (see D75034), 
which did not correctly identify the alignment of binary/ternary expressions.

Reviewed By: curdeius

Patch by: fickert

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index f3202bcb5bc1..d99107cb8b2c 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -1348,16 +1348,20 @@ void 
ContinuationIndenter::moveStatePastFakeLParens(LineState &State,
State.Stack.back().LastSpace);
 }
 
-// If BreakBeforeBinaryOperators is set, un-indent a bit to account for
-// the operator and keep the operands aligned
-if (Style.AlignOperands == FormatStyle::OAS_AlignAfterOperator &&
-Previous &&
+if (Previous &&
 (Previous->getPrecedence() == prec::Assignment ||
  Previous->is(tok::kw_return) ||
  (*I == prec::Conditional && Previous->is(tok::question) &&
   Previous->is(TT_ConditionalExpr))) &&
-!Newline)
-  NewParenState.UnindentOperator = true;
+!Newline) {
+  // If BreakBeforeBinaryOperators is set, un-indent a bit to account for
+  // the operator and keep the operands aligned
+  if (Style.AlignOperands == FormatStyle::OAS_AlignAfterOperator)
+NewParenState.UnindentOperator = true;
+  // Mark indentation as alignment if the expression is aligned.
+  if (Style.AlignOperands != FormatStyle::OAS_DontAlign)
+NewParenState.IsAligned = true;
+}
 
 // Do not indent relative to the fake parentheses inserted for "." or "->".
 // This is a special case to make the following to statements consistent:

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index d8642062fb6f..dcd9da77a390 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -11259,6 +11259,23 @@ TEST_F(FormatTest, ConfigurableUseOfTab) {
"\t}\n"
"};",
Tab);
+  Tab.AlignOperands = FormatStyle::OAS_Align;
+  verifyFormat("int aa =  +\n"
+   " ;",
+   Tab);
+  // no alignment
+  verifyFormat("int aa =\n"
+   "\t;",
+   Tab);
+  verifyFormat("return  ? 111\n"
+   "   : bb ? 222\n"
+   ": 333;",
+   Tab);
+  Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
+  Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
+  verifyFormat("int aa = \n"
+   "   + ;",
+   Tab);
 }
 
 TEST_F(FormatTest, ZeroTabWidth) {



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


[clang-tools-extra] r283986 - [clang-tidy-vs] Fix ClangTidy extension name in the manifest.

2016-10-12 Thread Marek Kurdej via cfe-commits
Author: mkurdej
Date: Wed Oct 12 03:32:59 2016
New Revision: 283986

URL: http://llvm.org/viewvc/llvm-project?rev=283986&view=rev
Log:
[clang-tidy-vs] Fix ClangTidy extension name in the manifest.

Modified:
clang-tools-extra/trunk/clang-tidy-vs/source.extension.vsixmanifest.in

Modified: clang-tools-extra/trunk/clang-tidy-vs/source.extension.vsixmanifest.in
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy-vs/source.extension.vsixmanifest.in?rev=283986&r1=283985&r2=283986&view=diff
==
--- clang-tools-extra/trunk/clang-tidy-vs/source.extension.vsixmanifest.in 
(original)
+++ clang-tools-extra/trunk/clang-tidy-vs/source.extension.vsixmanifest.in Wed 
Oct 12 03:32:59 2016
@@ -1,7 +1,7 @@
 
 http://schemas.microsoft.com/developer/vsx-schema/2010";>
   
-ClangFormat
+ClangTidy
 LLVM
 @CLANG_TIDY_VS_VERSION@
 A static analysis tool for C/C++ 
code.


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


[clang-tools-extra] r284212 - [clang-tidy] Fix readability-braces-around-statements false positive

2016-10-14 Thread Marek Kurdej via cfe-commits
Author: mkurdej
Date: Fri Oct 14 03:10:08 2016
New Revision: 284212

URL: http://llvm.org/viewvc/llvm-project?rev=284212&view=rev
Log:
[clang-tidy] Fix readability-braces-around-statements false positive

Summary:
This fixes a false-positive e.g. when string literals are returned from if 
statement.

This patch includes as well a small fix to includes and renames of the test 
suite that collided with the name of the check.

Reviewers: alexfh, hokein

Subscribers: hokein

Tags: #clang-tools-extra

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

Modified:
clang-tools-extra/trunk/clang-tidy/modernize/UseUsingCheck.cpp

clang-tools-extra/trunk/clang-tidy/readability/BracesAroundStatementsCheck.cpp
clang-tools-extra/trunk/unittests/clang-tidy/ReadabilityModuleTest.cpp

Modified: clang-tools-extra/trunk/clang-tidy/modernize/UseUsingCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/modernize/UseUsingCheck.cpp?rev=284212&r1=284211&r2=284212&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/modernize/UseUsingCheck.cpp (original)
+++ clang-tools-extra/trunk/clang-tidy/modernize/UseUsingCheck.cpp Fri Oct 14 
03:10:08 2016
@@ -8,7 +8,8 @@
 
//===--===//
 
 #include "UseUsingCheck.h"
-#include "../utils/LexerUtils.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/Lex/Lexer.h"
 
 using namespace clang::ast_matchers;
 

Modified: 
clang-tools-extra/trunk/clang-tidy/readability/BracesAroundStatementsCheck.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/readability/BracesAroundStatementsCheck.cpp?rev=284212&r1=284211&r2=284212&view=diff
==
--- 
clang-tools-extra/trunk/clang-tidy/readability/BracesAroundStatementsCheck.cpp 
(original)
+++ 
clang-tools-extra/trunk/clang-tidy/readability/BracesAroundStatementsCheck.cpp 
Fri Oct 14 03:10:08 2016
@@ -61,7 +61,7 @@ SourceLocation findEndLocation(SourceLoc
   bool SkipEndWhitespaceAndComments = true;
   tok::TokenKind TokKind = getTokenKind(Loc, SM, Context);
   if (TokKind == tok::NUM_TOKENS || TokKind == tok::semi ||
-  TokKind == tok::r_brace) {
+  TokKind == tok::r_brace || isStringLiteral(TokKind)) {
 // If we are at ";" or "}", we found the last token. We could use as well
 // `if (isa(S))`, but it wouldn't work for nested statements.
 SkipEndWhitespaceAndComments = false;

Modified: clang-tools-extra/trunk/unittests/clang-tidy/ReadabilityModuleTest.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/unittests/clang-tidy/ReadabilityModuleTest.cpp?rev=284212&r1=284211&r2=284212&view=diff
==
--- clang-tools-extra/trunk/unittests/clang-tidy/ReadabilityModuleTest.cpp 
(original)
+++ clang-tools-extra/trunk/unittests/clang-tidy/ReadabilityModuleTest.cpp Fri 
Oct 14 03:10:08 2016
@@ -15,9 +15,9 @@ TEST(NamespaceCommentCheckTest, Basic) {
 runCheckOnCode("namespace i {\n}"));
   EXPECT_EQ("namespace {\n} // namespace",
 runCheckOnCode("namespace {\n}"));
-  EXPECT_EQ(
-  "namespace i { namespace j {\n} // namespace j\n } // namespace i",
-  runCheckOnCode("namespace i { namespace j {\n} 
}"));
+  EXPECT_EQ("namespace i { namespace j {\n} // namespace j\n } // namespace i",
+runCheckOnCode(
+"namespace i { namespace j {\n} }"));
 }
 
 TEST(NamespaceCommentCheckTest, SingleLineNamespaces) {
@@ -49,10 +49,11 @@ TEST(NamespaceCommentCheckTest, CheckExi
 "} // Anonymous namespace.",
 runCheckOnCode("namespace {\n"
   "} // Anonymous 
namespace."));
-  EXPECT_EQ("namespace q {\n"
-"} // namespace q",
-runCheckOnCode("namespace q {\n"
-  "} // anonymous namespace 
q"));
+  EXPECT_EQ(
+  "namespace q {\n"
+  "} // namespace q",
+  runCheckOnCode("namespace q {\n"
+"} // anonymous namespace q"));
   EXPECT_EQ(
   "namespace My_NameSpace123 {\n"
   "} // namespace My_NameSpace123",
@@ -97,7 +98,7 @@ TEST(NamespaceCommentCheckTest, FixWrong
   "} // random text"));
 }
 
-TEST(BracesAroundStatementsCheck, IfWithComments) {
+TEST(BracesAroundStatementsCheckTest, IfWithComments) {
   EXPECT_EQ("int main() {\n"
 "  if (false /*dummy token*/) {\n"
 "// comment\n"
@@ -134,7 +135,7 @@ TEST(BracesAroundStatementsCheck, IfWith
 "}"));
 }
 
-TEST(BracesAroundStatementsCheck, If) {
+TEST(BracesAroundStatementsCheckTest, If) {
   EXPECT_NO_CHANGES(BracesAroundStatementsCheck, "int main() {\n"
   

[clang] 14c30c7 - [clang-format] Avoid crash in LevelIndentTracker.

2022-07-07 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-07-07T10:15:45+02:00
New Revision: 14c30c70c4595d8f410c74a72357a5a31fdd5507

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

LOG: [clang-format] Avoid crash in LevelIndentTracker.

Fixes https://github.com/llvm/llvm-project/issues/56352.

Reviewed By: HazardyKnusperkeks, owenpan, MyDeveloperDay

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

Added: 


Modified: 
clang/lib/Format/UnwrappedLineFormatter.cpp
clang/unittests/Format/FormatTestSelective.cpp

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineFormatter.cpp 
b/clang/lib/Format/UnwrappedLineFormatter.cpp
index 22509a5042465..9a6f8884fcec3 100644
--- a/clang/lib/Format/UnwrappedLineFormatter.cpp
+++ b/clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -66,7 +66,6 @@ class LevelIndentTracker {
   (Style.PPIndentWidth >= 0) ? Style.PPIndentWidth : Style.IndentWidth;
   Indent = Line.Level * IndentWidth + AdditionalIndent;
 } else {
-  IndentForLevel.resize(Line.Level + 1);
   Indent = getIndent(Line.Level);
 }
 if (static_cast(Indent) + Offset >= 0)
@@ -91,6 +90,7 @@ class LevelIndentTracker {
 unsigned LevelIndent = Line.First->OriginalColumn;
 if (static_cast(LevelIndent) - Offset >= 0)
   LevelIndent -= Offset;
+assert(Line.Level < IndentForLevel.size());
 if ((!Line.First->is(tok::comment) || IndentForLevel[Line.Level] == -1) &&
 !Line.InPPDirective) {
   IndentForLevel[Line.Level] = LevelIndent;

diff  --git a/clang/unittests/Format/FormatTestSelective.cpp 
b/clang/unittests/Format/FormatTestSelective.cpp
index 2725e4cf776f6..86ed7aba1913d 100644
--- a/clang/unittests/Format/FormatTestSelective.cpp
+++ b/clang/unittests/Format/FormatTestSelective.cpp
@@ -609,6 +609,14 @@ TEST_F(FormatTestSelective, DontAssert) {
  "  return a == 8 ? 32 : 16;\n"
  "}\n";
   EXPECT_EQ(Code, format(Code, 40, 0));
+
+  // https://llvm.org/PR56352
+  Style.CompactNamespaces = true;
+  Style.NamespaceIndentation = FormatStyle::NI_All;
+  Code = "\n"
+ "namespace ns1 { namespace ns2 {\n"
+ "}}";
+  EXPECT_EQ(Code, format(Code, 0, 0));
 }
 
 } // end namespace



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


[clang] 311a00c - [clang-format] Clean up DefinitionBlockSeparatorTest. NFC.

2022-03-25 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-03-25T10:59:46+01:00
New Revision: 311a00c39046ed3f84cd31ffcd513975d3000402

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

LOG: [clang-format] Clean up DefinitionBlockSeparatorTest. NFC.

Added: 


Modified: 
clang/unittests/Format/DefinitionBlockSeparatorTest.cpp

Removed: 




diff  --git a/clang/unittests/Format/DefinitionBlockSeparatorTest.cpp 
b/clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
index 582b62e445df9..53a3c57ad59fa 100644
--- a/clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
+++ b/clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
@@ -56,17 +56,15 @@ class DefinitionBlockSeparatorTest : public ::testing::Test 
{
   InverseStyle.SeparateDefinitionBlocks = FormatStyle::SDS_Never;
 else
   InverseStyle.SeparateDefinitionBlocks = FormatStyle::SDS_Always;
-EXPECT_EQ(ExpectedCode.str(), separateDefinitionBlocks(ExpectedCode, 
Style))
+EXPECT_EQ(ExpectedCode, separateDefinitionBlocks(ExpectedCode, Style))
 << "Expected code is not stable";
-std::string InverseResult =
-separateDefinitionBlocks(ExpectedCode, InverseStyle);
-EXPECT_NE(ExpectedCode.str(), InverseResult)
+EXPECT_NE(ExpectedCode,
+  separateDefinitionBlocks(ExpectedCode, InverseStyle))
 << "Inverse formatting makes no 
diff erence";
 std::string CodeToFormat =
 HasOriginalCode ? Code.str() : removeEmptyLines(Code);
 std::string Result = separateDefinitionBlocks(CodeToFormat, Style);
-EXPECT_EQ(ExpectedCode.str(), Result) << "Test failed. Formatted:\n"
-  << Result;
+EXPECT_EQ(ExpectedCode, Result) << "Test failed. Formatted:\n" << Result;
   }
 
   static std::string removeEmptyLines(llvm::StringRef Code) {



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


[clang] 7161672 - [clang-format] Correctly attach enum braces with ShortEnums disabled

2021-07-28 Thread Marek Kurdej via cfe-commits

Author: Luna Kirkby
Date: 2021-07-28T10:29:15+02:00
New Revision: 71616722d4092f88861e9eb337e2902bbab2cbd4

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

LOG: [clang-format] Correctly attach enum braces with ShortEnums disabled

Previously, with AllowShortEnumsOnASingleLine disabled, enums that would have 
otherwise fit on a single line would always put the opening brace on its own 
line.
This patch ensures that these enums will only put the brace on its own line if 
the existing attachment rules indicate that it should.

Reviewed By: HazardyKnusperkeks, curdeius

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

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Format/Format.h
clang/lib/Format/UnwrappedLineParser.cpp
clang/unittests/Format/FormatTest.cpp
clang/unittests/Format/FormatTestCSharp.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 19a4e8f9ece39..ca3ad908fa099 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -153,7 +153,8 @@ AST Matchers
 clang-format
 
 
-- ...
+- Option ``AllowShortEnumsOnASingleLine: false`` has been improved, it now
+  correctly places the opening brace according to ``BraceWrapping.AfterEnum``.
 
 libclang
 

diff  --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index c424e79a971cf..0e2193596daf7 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -544,8 +544,7 @@ struct FormatStyle {
   ///   enum { A, B } myEnum;
   ///
   ///   false:
-  ///   enum
-  ///   {
+  ///   enum {
   /// A,
   /// B
   ///   } myEnum;

diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 103e3559b1208..d6b1ebb1239df 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -2515,6 +2515,8 @@ bool UnwrappedLineParser::parseEnum() {
   if (FormatTok->Tok.is(tok::kw_enum))
 nextToken();
 
+  const FormatToken &InitialToken = *FormatTok;
+
   // In TypeScript, "enum" can also be used as property name, e.g. in interface
   // declarations. An "enum" keyword followed by a colon would be a syntax
   // error and thus assume it is just an identifier.
@@ -2561,7 +2563,8 @@ bool UnwrappedLineParser::parseEnum() {
 return true;
   }
 
-  if (!Style.AllowShortEnumsOnASingleLine)
+  if (!Style.AllowShortEnumsOnASingleLine &&
+  ShouldBreakBeforeBrace(Style, InitialToken))
 addUnwrappedLine();
   // Parse enum body.
   nextToken();

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 3adf42d34cf13..a4e5f9dce9b8d 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -2451,6 +2451,14 @@ TEST_F(FormatTest, ShortEnums) {
   Style.AllowShortEnumsOnASingleLine = true;
   verifyFormat("enum { A, B, C } ShortEnum1, ShortEnum2;", Style);
   Style.AllowShortEnumsOnASingleLine = false;
+  verifyFormat("enum {\n"
+   "  A,\n"
+   "  B,\n"
+   "  C\n"
+   "} ShortEnum1, ShortEnum2;",
+   Style);
+  Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+  Style.BraceWrapping.AfterEnum = true;
   verifyFormat("enum\n"
"{\n"
"  A,\n"
@@ -22123,8 +22131,7 @@ TEST_F(FormatTest, IndentAccessModifiers) {
Style);
   // Enumerations are not records and should be unaffected.
   Style.AllowShortEnumsOnASingleLine = false;
-  verifyFormat("enum class E\n"
-   "{\n"
+  verifyFormat("enum class E {\n"
"  A,\n"
"  B\n"
"};\n",

diff  --git a/clang/unittests/Format/FormatTestCSharp.cpp 
b/clang/unittests/Format/FormatTestCSharp.cpp
index 3c990339cf748..8cd29e5548175 100644
--- a/clang/unittests/Format/FormatTestCSharp.cpp
+++ b/clang/unittests/Format/FormatTestCSharp.cpp
@@ -402,8 +402,7 @@ TEST_F(FormatTestCSharp, CSharpRegions) {
 }
 
 TEST_F(FormatTestCSharp, CSharpKeyWordEscaping) {
-  verifyFormat("public enum var\n"
-   "{\n"
+  verifyFormat("public enum var {\n"
"none,\n"
"@string,\n"
"bool,\n"



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


[clang] b44eb20 - [clang-format] Refactor condition in AnnotatingParser::modifyContext(). NFC.

2022-03-11 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-03-11T13:12:43+01:00
New Revision: b44eb207e96a5e20aecbb6084147ae97e3eabd22

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

LOG: [clang-format] Refactor condition in AnnotatingParser::modifyContext(). 
NFC.

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 8f5f4e0f43362..1c662c9a909c9 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1506,15 +1506,24 @@ class AnnotatingParser {
   };
 
   void modifyContext(const FormatToken &Current) {
-if (Current.getPrecedence() == prec::Assignment &&
-!Line.First->isOneOf(tok::kw_template, tok::kw_using, tok::kw_return) 
&&
-// Type aliases use `type X = ...;` in TypeScript and can be exported
-// using `export type ...`.
-!(Style.isJavaScript() &&
+auto AssignmentStartsExpression = [&]() {
+  if (Current.getPrecedence() != prec::Assignment)
+return false;
+
+  if (Line.First->isOneOf(tok::kw_template, tok::kw_using, tok::kw_return))
+return false;
+
+  // Type aliases use `type X = ...;` in TypeScript and can be exported
+  // using `export type ...`.
+  if (Style.isJavaScript() &&
   (Line.startsWith(Keywords.kw_type, tok::identifier) ||
-   Line.startsWith(tok::kw_export, Keywords.kw_type,
-   tok::identifier))) &&
-(!Current.Previous || Current.Previous->isNot(tok::kw_operator))) {
+   Line.startsWith(tok::kw_export, Keywords.kw_type, tok::identifier)))
+return false;
+
+  return !Current.Previous || Current.Previous->isNot(tok::kw_operator);
+};
+
+if (AssignmentStartsExpression()) {
   Contexts.back().IsExpression = true;
   if (!Line.startsWith(TT_UnaryOperator)) {
 for (FormatToken *Previous = Current.Previous;



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


[clang] 596fa2d - [clang-format] Handle attributes before case label.

2022-03-13 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-03-13T21:53:40+01:00
New Revision: 596fa2d90044841c33b9a0e6b17406c2a45077a2

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

LOG: [clang-format] Handle attributes before case label.

Fixes https://github.com/llvm/llvm-project/issues/53110.

Reviewed By: MyDeveloperDay, HazardyKnusperkeks, owenpan

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 3a245b8b5fa0d..47e794c7b1ca6 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -480,6 +480,10 @@ bool UnwrappedLineParser::parseLevel(bool HasOpeningBrace,
   unsigned StatementCount = 0;
   bool SwitchLabelEncountered = false;
   do {
+if (FormatTok->getType() == TT_AttributeMacro) {
+  nextToken();
+  continue;
+}
 tok::TokenKind kind = FormatTok->Tok.getKind();
 if (FormatTok->getType() == TT_MacroBlockBegin)
   kind = tok::l_brace;
@@ -569,6 +573,8 @@ bool UnwrappedLineParser::parseLevel(bool HasOpeningBrace,
 parseCSharpAttribute();
 break;
   }
+  if (handleCppAttributes())
+break;
   LLVM_FALLTHROUGH;
 default:
   ParseDefault();
@@ -1390,9 +1396,11 @@ void 
UnwrappedLineParser::parseStructuralElement(IfStmtKind *IfKind,
 // e.g. "default void f() {}" in a Java interface.
 break;
   case tok::kw_case:
-if (Style.isJavaScript() && Line->MustBeDeclaration)
+if (Style.isJavaScript() && Line->MustBeDeclaration) {
   // 'case: string' field declaration.
+  nextToken();
   break;
+}
 parseCaseLabel();
 return;
   case tok::kw_try:
@@ -1813,6 +1821,12 @@ void 
UnwrappedLineParser::parseStructuralElement(IfStmtKind *IfKind,
 case tok::kw_new:
   parseNew();
   break;
+case tok::kw_case:
+  if (Style.isJavaScript() && Line->MustBeDeclaration)
+// 'case: string' field declaration.
+break;
+  parseCaseLabel();
+  break;
 default:
   nextToken();
   break;
@@ -2376,17 +2390,24 @@ static void markOptionalBraces(FormatToken *LeftBrace) {
   RightBrace->Optional = true;
 }
 
+void UnwrappedLineParser::handleAttributes() {
+  // Handle AttributeMacro, e.g. `if (x) UNLIKELY`.
+  if (FormatTok->is(TT_AttributeMacro))
+nextToken();
+  handleCppAttributes();
+}
+
+bool UnwrappedLineParser::handleCppAttributes() {
+  // Handle [[likely]] / [[unlikely]] attributes.
+  if (FormatTok->is(tok::l_square) && tryToParseSimpleAttribute()) {
+parseSquare();
+return true;
+  }
+  return false;
+}
+
 FormatToken *UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind,
   bool KeepBraces) {
-  auto HandleAttributes = [this]() {
-// Handle AttributeMacro, e.g. `if (x) UNLIKELY`.
-if (FormatTok->is(TT_AttributeMacro))
-  nextToken();
-// Handle [[likely]] / [[unlikely]] attributes.
-if (FormatTok->is(tok::l_square) && tryToParseSimpleAttribute())
-  parseSquare();
-  };
-
   assert(FormatTok->is(tok::kw_if) && "'if' expected");
   nextToken();
   if (FormatTok->is(tok::exclaim))
@@ -2399,7 +2420,7 @@ FormatToken 
*UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind,
 if (FormatTok->is(tok::l_paren))
   parseParens();
   }
-  HandleAttributes();
+  handleAttributes();
 
   bool NeedsUnwrappedLine = false;
   keepAncestorBraces();
@@ -2436,7 +2457,7 @@ FormatToken 
*UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind,
   Kind = IfStmtKind::IfElse;
 }
 nextToken();
-HandleAttributes();
+handleAttributes();
 if (FormatTok->is(tok::l_brace)) {
   ElseLeftBrace = FormatTok;
   CompoundStatementIndenter Indenter(this, Style, Line->Level);

diff  --git a/clang/lib/Format/UnwrappedLineParser.h 
b/clang/lib/Format/UnwrappedLineParser.h
index 5cc01398a5457..798bae24ad075 100644
--- a/clang/lib/Format/UnwrappedLineParser.h
+++ b/clang/lib/Format/UnwrappedLineParser.h
@@ -121,6 +121,8 @@ class UnwrappedLineParser {
   void parseSquare(bool LambdaIntroducer = false);
   void keepAncestorBraces();
   void parseUnbracedBody(bool CheckEOF = false);
+  void handleAttributes();
+  bool handleCppAttributes();
   FormatToken *parseIfThenElse(IfStmtKind *IfKind, bool KeepBraces = false);
   void parseTryCatch();
   void parseForOrWhileLoop();

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 37a42382e8f85..430a195f60255 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unit

[clang] 36d13d3 - [clang-format] Add space to comments starting with '#'.

2022-03-13 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-03-13T21:56:22+01:00
New Revision: 36d13d3f8adb3d1a6bae71370afa23d11a94dc78

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

LOG: [clang-format] Add space to comments starting with '#'.

Fixes https://github.com/llvm/llvm-project/issues/35116.

Reviewed By: MyDeveloperDay, HazardyKnusperkeks, owenpan

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/BreakableToken.cpp 
b/clang/lib/Format/BreakableToken.cpp
index 967ddeb82383a..ae084e9e14544 100644
--- a/clang/lib/Format/BreakableToken.cpp
+++ b/clang/lib/Format/BreakableToken.cpp
@@ -779,11 +779,14 @@ BreakableLineCommentSection::BreakableLineCommentSection(
 const char FirstCommentChar = Lines[i][IndentPrefix.size()];
 const unsigned FirstCharByteSize =
 encoding::getCodePointNumBytes(FirstCommentChar, Encoding);
-return encoding::columnWidth(
-   Lines[i].substr(IndentPrefix.size(), FirstCharByteSize),
-   Encoding) == 1 &&
-   (FirstCommentChar == '\\' || isPunctuation(FirstCommentChar) ||
-isHorizontalWhitespace(FirstCommentChar));
+if (encoding::columnWidth(
+Lines[i].substr(IndentPrefix.size(), FirstCharByteSize),
+Encoding) != 1)
+  return false;
+if (FirstCommentChar == '#')
+  return false;
+return FirstCommentChar == '\\' || isPunctuation(FirstCommentChar) ||
+   isHorizontalWhitespace(FirstCommentChar);
   };
 
   // On the first line of the comment section we calculate how many spaces

diff  --git a/clang/unittests/Format/FormatTestComments.cpp 
b/clang/unittests/Format/FormatTestComments.cpp
index f83ffb393ac2f..27cc6013611c2 100644
--- a/clang/unittests/Format/FormatTestComments.cpp
+++ b/clang/unittests/Format/FormatTestComments.cpp
@@ -91,6 +91,9 @@ TEST_F(FormatTestComments, UnderstandsSingleLineComments) {
"// line 2\n"
"void f() {}\n");
 
+  EXPECT_EQ("// comment\n", format("//comment\n"));
+  EXPECT_EQ("// #comment\n", format("//#comment\n"));
+
   EXPECT_EQ("// comment\n"
 "// clang-format on\n",
 format("//comment\n"
@@ -3302,6 +3305,7 @@ TEST_F(FormatTestComments, SpaceAtLineCommentBegin) {
 format(NoTextInComment, Style));
 
   Style.SpacesInLineCommentPrefix.Minimum = 0;
+  EXPECT_EQ("//#comment", format("//#comment", Style));
   EXPECT_EQ("//\n"
 "\n"
 "void foo() { //\n"
@@ -3310,6 +3314,7 @@ TEST_F(FormatTestComments, SpaceAtLineCommentBegin) {
 format(NoTextInComment, Style));
 
   Style.SpacesInLineCommentPrefix.Minimum = 5;
+  EXPECT_EQ("// #comment", format("//#comment", Style));
   EXPECT_EQ("//\n"
 "\n"
 "void foo() { //\n"
@@ -3463,6 +3468,7 @@ TEST_F(FormatTestComments, SpaceAtLineCommentBegin) {
 format(Code, Style));
 
   Style.SpacesInLineCommentPrefix = {0, 0};
+  EXPECT_EQ("//#comment", format("//   #comment", Style));
   EXPECT_EQ("//Free comment without space\n"
 "\n"
 "//Free comment with 3 spaces\n"



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


[clang] a140b71 - [clang-format] Correctly format variable templates.

2022-03-13 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-03-13T22:00:17+01:00
New Revision: a140b7104fdae0d9eff5b18efbc784754e0ca274

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

LOG: [clang-format] Correctly format variable templates.

Fixes https://github.com/llvm/llvm-project/issues/54257.

Reviewed By: MyDeveloperDay, HazardyKnusperkeks, owenpan

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 1c662c9a909c9..77ef54e0e2d59 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1510,8 +1510,30 @@ class AnnotatingParser {
   if (Current.getPrecedence() != prec::Assignment)
 return false;
 
-  if (Line.First->isOneOf(tok::kw_template, tok::kw_using, tok::kw_return))
+  if (Line.First->isOneOf(tok::kw_using, tok::kw_return))
 return false;
+  if (Line.First->is(tok::kw_template)) {
+// `template` keyword can start a variable template.
+const FormatToken *Tok = Line.First->getNextNonComment();
+assert(Tok); // Current token is on the same line.
+if (Tok->isNot(TT_TemplateOpener)) {
+  // Explicit template instantiations do not have `<>`.
+  return false;
+}
+
+Tok = Tok->MatchingParen;
+if (!Tok)
+  return false;
+Tok = Tok->getNextNonComment();
+if (!Tok)
+  return false;
+
+if (Tok->isOneOf(tok::kw_class, tok::kw_enum, tok::kw_concept,
+ tok::kw_struct, tok::kw_using))
+  return false;
+
+return true;
+  }
 
   // Type aliases use `type X = ...;` in TypeScript and can be exported
   // using `export type ...`.

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 430a195f60255..45e8c0b79cfb2 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -25525,6 +25525,12 @@ TEST_F(FormatTest, 
AlignArrayOfStructuresRightAlignmentNonSquare) {
Style);
 }
 
+TEST_F(FormatTest, FormatsVariableTemplates) {
+  verifyFormat("inline bool var = is_integral_v && is_signed_v;");
+  verifyFormat("template  "
+   "inline bool var = is_integral_v && is_signed_v;");
+}
+
 } // namespace
 } // namespace format
 } // namespace clang

diff  --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 17801e4bb9839..7e753bc5a34d5 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -117,6 +117,31 @@ TEST_F(TokenAnnotatorTest, UnderstandsEnums) {
   EXPECT_TOKEN(Tokens[2], tok::l_brace, TT_EnumLBrace);
 }
 
+TEST_F(TokenAnnotatorTest, UnderstandsDefaultedAndDeletedFunctions) {
+  auto Tokens = annotate("auto operator<=>(const T &) const & = default;");
+  EXPECT_EQ(Tokens.size(), 14u) << Tokens;
+  EXPECT_TOKEN(Tokens[9], tok::amp, TT_PointerOrReference);
+
+  Tokens = annotate("template  void F(T) && = delete;");
+  EXPECT_EQ(Tokens.size(), 15u) << Tokens;
+  EXPECT_TOKEN(Tokens[10], tok::ampamp, TT_PointerOrReference);
+}
+
+TEST_F(TokenAnnotatorTest, UnderstandsVariables) {
+  auto Tokens =
+  annotate("inline bool var = is_integral_v && is_signed_v;");
+  EXPECT_EQ(Tokens.size(), 15u) << Tokens;
+  EXPECT_TOKEN(Tokens[8], tok::ampamp, TT_BinaryOperator);
+}
+
+TEST_F(TokenAnnotatorTest, UnderstandsVariableTemplates) {
+  auto Tokens =
+  annotate("template  "
+   "inline bool var = is_integral_v && is_signed_v;");
+  EXPECT_EQ(Tokens.size(), 20u) << Tokens;
+  EXPECT_TOKEN(Tokens[13], tok::ampamp, TT_BinaryOperator);
+}
+
 TEST_F(TokenAnnotatorTest, UnderstandsLBracesInMacroDefinition) {
   auto Tokens = annotate("#define BEGIN NS {");
   EXPECT_EQ(Tokens.size(), 6u) << Tokens;



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


[clang] 0570af1 - [clang-format] Fix incorrect assertion on macro definitions with keyword class.

2022-03-13 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-03-13T22:17:48+01:00
New Revision: 0570af17585d98be0c12f6760118eb94071d9c26

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

LOG: [clang-format] Fix incorrect assertion on macro definitions with keyword 
class.

Fixes https://github.com/llvm/llvm-project/issues/54348.

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineFormatter.cpp 
b/clang/lib/Format/UnwrappedLineFormatter.cpp
index 5b5439901b2f7..1393a2a321183 100644
--- a/clang/lib/Format/UnwrappedLineFormatter.cpp
+++ b/clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -484,7 +484,8 @@ class LineJoiner {
   } else {
 // Try to merge a block with left brace unwrapped that wasn't yet
 // covered.
-assert(!TheLine->First->isOneOf(tok::kw_class, tok::kw_enum,
+assert(TheLine->InPPDirective ||
+   !TheLine->First->isOneOf(tok::kw_class, tok::kw_enum,
 tok::kw_struct));
 ShouldMerge = !Style.BraceWrapping.AfterFunction ||
   (NextLine.First->is(tok::r_brace) &&

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 45e8c0b79cfb2..baa3993805bcb 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -1877,6 +1877,13 @@ TEST_F(FormatTest, UnderstandsMacros) {
   verifyFormat("#define __except(x)");
   verifyFormat("#define __try(x)");
 
+  // https://llvm.org/PR54348.
+  verifyFormat(
+  "#define A"
+  "  "
+  "\\\n"
+  "  class & {}");
+
   FormatStyle Style = getLLVMStyle();
   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
   Style.BraceWrapping.AfterFunction = true;



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


[clang] 2507e0a - [clang-format] Clean up UnwrappedLineParser::parseRecord. NFC.

2022-03-14 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-03-14T11:59:52+01:00
New Revision: 2507e0a257991fd46bd847c8fa0964bc70891add

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

LOG: [clang-format] Clean up UnwrappedLineParser::parseRecord. NFC.

Added: 


Modified: 
clang/lib/Format/UnwrappedLineParser.cpp

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 47e794c7b1ca6..b03296c7e02d9 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -3511,7 +3511,7 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
   // (this would still leave us with an ambiguity between template function
   // and class declarations).
   if (FormatTok->isOneOf(tok::colon, tok::less)) {
-while (!eof()) {
+do {
   if (FormatTok->is(tok::l_brace)) {
 calculateBraceTypes(/*ExpectClassBody=*/true);
 if (!tryToParseBracedList())
@@ -3525,6 +3525,9 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
   // it was probably a pointer to an array: int (*)[].
   if (!tryToParseLambda())
 break;
+} else {
+  parseSquare();
+  continue;
 }
   }
   if (FormatTok->is(tok::semi))
@@ -3536,7 +3539,7 @@ void UnwrappedLineParser::parseRecord(bool ParseAsExpr) {
 break;
   }
   nextToken();
-}
+} while (!eof());
   }
 
   auto GetBraceType = [](const FormatToken &RecordTok) {



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


[clang] a6b2f50 - Revert "[clang-format] Correctly format variable templates."

2022-03-14 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-03-14T16:04:09+01:00
New Revision: a6b2f50fb47da3baeee10b1906da6e30ac5d26ec

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

LOG: Revert "[clang-format] Correctly format variable templates."

This reverts commit a140b7104fdae0d9eff5b18efbc784754e0ca274.

It provoked the bug https://github.com/llvm/llvm-project/issues/54374.

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 6cf3681cdd9d5..0c760b5b2811d 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1526,30 +1526,8 @@ class AnnotatingParser {
   if (Current.getPrecedence() != prec::Assignment)
 return false;
 
-  if (Line.First->isOneOf(tok::kw_using, tok::kw_return))
+  if (Line.First->isOneOf(tok::kw_template, tok::kw_using, tok::kw_return))
 return false;
-  if (Line.First->is(tok::kw_template)) {
-// `template` keyword can start a variable template.
-const FormatToken *Tok = Line.First->getNextNonComment();
-assert(Tok); // Current token is on the same line.
-if (Tok->isNot(TT_TemplateOpener)) {
-  // Explicit template instantiations do not have `<>`.
-  return false;
-}
-
-Tok = Tok->MatchingParen;
-if (!Tok)
-  return false;
-Tok = Tok->getNextNonComment();
-if (!Tok)
-  return false;
-
-if (Tok->isOneOf(tok::kw_class, tok::kw_enum, tok::kw_concept,
- tok::kw_struct, tok::kw_using))
-  return false;
-
-return true;
-  }
 
   // Type aliases use `type X = ...;` in TypeScript and can be exported
   // using `export type ...`.

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index aadd24a0d6ca6..05427c6249749 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -25625,12 +25625,6 @@ TEST_F(FormatTest, 
AlignArrayOfStructuresRightAlignmentNonSquare) {
Style);
 }
 
-TEST_F(FormatTest, FormatsVariableTemplates) {
-  verifyFormat("inline bool var = is_integral_v && is_signed_v;");
-  verifyFormat("template  "
-   "inline bool var = is_integral_v && is_signed_v;");
-}
-
 } // namespace
 } // namespace format
 } // namespace clang

diff  --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index dd868be99f45e..dff8c04662601 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -117,31 +117,6 @@ TEST_F(TokenAnnotatorTest, UnderstandsEnums) {
   EXPECT_TOKEN(Tokens[2], tok::l_brace, TT_EnumLBrace);
 }
 
-TEST_F(TokenAnnotatorTest, UnderstandsDefaultedAndDeletedFunctions) {
-  auto Tokens = annotate("auto operator<=>(const T &) const & = default;");
-  EXPECT_EQ(Tokens.size(), 14u) << Tokens;
-  EXPECT_TOKEN(Tokens[9], tok::amp, TT_PointerOrReference);
-
-  Tokens = annotate("template  void F(T) && = delete;");
-  EXPECT_EQ(Tokens.size(), 15u) << Tokens;
-  EXPECT_TOKEN(Tokens[10], tok::ampamp, TT_PointerOrReference);
-}
-
-TEST_F(TokenAnnotatorTest, UnderstandsVariables) {
-  auto Tokens =
-  annotate("inline bool var = is_integral_v && is_signed_v;");
-  EXPECT_EQ(Tokens.size(), 15u) << Tokens;
-  EXPECT_TOKEN(Tokens[8], tok::ampamp, TT_BinaryOperator);
-}
-
-TEST_F(TokenAnnotatorTest, UnderstandsVariableTemplates) {
-  auto Tokens =
-  annotate("template  "
-   "inline bool var = is_integral_v && is_signed_v;");
-  EXPECT_EQ(Tokens.size(), 20u) << Tokens;
-  EXPECT_TOKEN(Tokens[13], tok::ampamp, TT_BinaryOperator);
-}
-
 TEST_F(TokenAnnotatorTest, UnderstandsLBracesInMacroDefinition) {
   auto Tokens = annotate("#define BEGIN NS {");
   EXPECT_EQ(Tokens.size(), 6u) << Tokens;



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


[clang] 126b37a - [clang-format] Correctly recognize arrays in template parameter list.

2022-03-15 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-03-15T11:33:13+01:00
New Revision: 126b37a713dc1c67cbc7dc8b5288b2f907c906a9

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

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

Fixes https://github.com/llvm/llvm-project/issues/54245.

Reviewed By: MyDeveloperDay, HazardyKnusperkeks, owenpan

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

Added: 


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

Removed: 




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

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



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


[clang] e60defb - [clang-format] Add regression tests for function ref qualifiers on operator definition. NFC.

2022-03-15 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-03-15T12:58:08+01:00
New Revision: e60defb931cfc333d143f6000a6a65ae4dc106a2

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

LOG: [clang-format] Add regression tests for function ref qualifiers on 
operator definition. NFC.

Fixes https://github.com/llvm/llvm-project/issues/54374.

Added: 


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

Removed: 




diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 354b60e27a5c7..557438de70fe0 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -9889,6 +9889,14 @@ TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
   verifyFormat("template \n"
"void F(T) && = delete;",
getGoogleStyle());
+  verifyFormat("template  void operator=(T) &;");
+  verifyFormat("template  void operator=(T) const &;");
+  verifyFormat("template  void operator=(T) &noexcept;");
+  verifyFormat("template  void operator=(T) & = default;");
+  verifyFormat("template  void operator=(T) &&;");
+  verifyFormat("template  void operator=(T) && = delete;");
+  verifyFormat("template  void operator=(T) & {}");
+  verifyFormat("template  void operator=(T) && {}");
 
   FormatStyle AlignLeft = getLLVMStyle();
   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
@@ -9909,6 +9917,14 @@ TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
   verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft);
   verifyFormat("void Fn(T const volatile&&) const volatile&& noexcept;",
AlignLeft);
+  verifyFormat("template  void operator=(T) &;", AlignLeft);
+  verifyFormat("template  void operator=(T) const&;", AlignLeft);
+  verifyFormat("template  void operator=(T) & noexcept;", 
AlignLeft);
+  verifyFormat("template  void operator=(T) & = default;", 
AlignLeft);
+  verifyFormat("template  void operator=(T) &&;", AlignLeft);
+  verifyFormat("template  void operator=(T) && = delete;", 
AlignLeft);
+  verifyFormat("template  void operator=(T) & {}", AlignLeft);
+  verifyFormat("template  void operator=(T) && {}", AlignLeft);
 
   FormatStyle AlignMiddle = getLLVMStyle();
   AlignMiddle.PointerAlignment = FormatStyle::PAS_Middle;
@@ -9930,6 +9946,14 @@ TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
   verifyFormat("void Fn(T const volatile &&) const volatile &&;", AlignMiddle);
   verifyFormat("void Fn(T const volatile &&) const volatile && noexcept;",
AlignMiddle);
+  verifyFormat("template  void operator=(T) &;", AlignMiddle);
+  verifyFormat("template  void operator=(T) const &;", 
AlignMiddle);
+  verifyFormat("template  void operator=(T) & noexcept;", 
AlignMiddle);
+  verifyFormat("template  void operator=(T) & = default;", 
AlignMiddle);
+  verifyFormat("template  void operator=(T) &&;", AlignMiddle);
+  verifyFormat("template  void operator=(T) && = delete;", 
AlignMiddle);
+  verifyFormat("template  void operator=(T) & {}", AlignMiddle);
+  verifyFormat("template  void operator=(T) && {}", AlignMiddle);
 
   FormatStyle Spaces = getLLVMStyle();
   Spaces.SpacesInCStyleCastParentheses = true;

diff  --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 5f346fa5f8bfa..9240e812ba927 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -159,6 +159,24 @@ TEST_F(TokenAnnotatorTest, UnderstandsDelete) {
   EXPECT_TOKEN(Tokens[7], tok::r_paren, TT_CastRParen);
 }
 
+TEST_F(TokenAnnotatorTest, UnderstandsFunctionRefQualifiers) {
+  auto Tokens = annotate("void f() &;");
+  EXPECT_EQ(Tokens.size(), 7u) << Tokens;
+  EXPECT_TOKEN(Tokens[4], tok::amp, TT_PointerOrReference);
+
+  Tokens = annotate("void operator=() &&;");
+  EXPECT_EQ(Tokens.size(), 8u) << Tokens;
+  EXPECT_TOKEN(Tokens[5], tok::ampamp, TT_PointerOrReference);
+
+  Tokens = annotate("template  void f() &;");
+  EXPECT_EQ(Tokens.size(), 12u) << Tokens;
+  EXPECT_TOKEN(Tokens[9], tok::amp, TT_PointerOrReference);
+
+  Tokens = annotate("template  void operator=() &;");
+  EXPECT_EQ(Tokens.size(), 13u) << Tokens;
+  EXPECT_TOKEN(Tokens[10], tok::amp, TT_PointerOrReference);
+}
+
 TEST_F(TokenAnnotatorTest, UnderstandsRequiresClausesAndConcepts) {
   auto Tokens = annotate("template \n"
  "concept C = (Foo && Bar) && (Bar && Baz);");



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


[clang] 3227aa3 - [clang-format] Correctly format variable templates.

2022-03-15 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-03-15T13:16:56+01:00
New Revision: 3227aa3aa83440ff94a3b13a29623e03b05098f2

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

LOG: [clang-format] Correctly format variable templates.

Fixes https://github.com/llvm/llvm-project/issues/54257.

Reviewed By: MyDeveloperDay, HazardyKnusperkeks, owenpan

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 0c760b5b2811d..f0a17af677016 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1526,8 +1526,36 @@ class AnnotatingParser {
   if (Current.getPrecedence() != prec::Assignment)
 return false;
 
-  if (Line.First->isOneOf(tok::kw_template, tok::kw_using, tok::kw_return))
+  if (Line.First->isOneOf(tok::kw_using, tok::kw_return))
 return false;
+  if (Line.First->is(tok::kw_template)) {
+assert(Current.Previous);
+if (Current.Previous->is(tok::kw_operator)) {
+  // `template ... operator=` cannot be an expression.
+  return false;
+}
+
+// `template` keyword can start a variable template.
+const FormatToken *Tok = Line.First->getNextNonComment();
+assert(Tok); // Current token is on the same line.
+if (Tok->isNot(TT_TemplateOpener)) {
+  // Explicit template instantiations do not have `<>`.
+  return false;
+}
+
+Tok = Tok->MatchingParen;
+if (!Tok)
+  return false;
+Tok = Tok->getNextNonComment();
+if (!Tok)
+  return false;
+
+if (Tok->isOneOf(tok::kw_class, tok::kw_enum, tok::kw_concept,
+ tok::kw_struct, tok::kw_using))
+  return false;
+
+return true;
+  }
 
   // Type aliases use `type X = ...;` in TypeScript and can be exported
   // using `export type ...`.

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 557438de70fe0..459cbf1c7681c 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -25657,6 +25657,12 @@ TEST_F(FormatTest, 
AlignArrayOfStructuresRightAlignmentNonSquare) {
Style);
 }
 
+TEST_F(FormatTest, FormatsVariableTemplates) {
+  verifyFormat("inline bool var = is_integral_v && is_signed_v;");
+  verifyFormat("template  "
+   "inline bool var = is_integral_v && is_signed_v;");
+}
+
 } // namespace
 } // namespace format
 } // namespace clang

diff  --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 9240e812ba927..cc624d0760d12 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -131,6 +131,31 @@ TEST_F(TokenAnnotatorTest, UnderstandsEnums) {
   EXPECT_TOKEN(Tokens[2], tok::l_brace, TT_EnumLBrace);
 }
 
+TEST_F(TokenAnnotatorTest, UnderstandsDefaultedAndDeletedFunctions) {
+  auto Tokens = annotate("auto operator<=>(const T &) const & = default;");
+  EXPECT_EQ(Tokens.size(), 14u) << Tokens;
+  EXPECT_TOKEN(Tokens[9], tok::amp, TT_PointerOrReference);
+
+  Tokens = annotate("template  void F(T) && = delete;");
+  EXPECT_EQ(Tokens.size(), 15u) << Tokens;
+  EXPECT_TOKEN(Tokens[10], tok::ampamp, TT_PointerOrReference);
+}
+
+TEST_F(TokenAnnotatorTest, UnderstandsVariables) {
+  auto Tokens =
+  annotate("inline bool var = is_integral_v && is_signed_v;");
+  EXPECT_EQ(Tokens.size(), 15u) << Tokens;
+  EXPECT_TOKEN(Tokens[8], tok::ampamp, TT_BinaryOperator);
+}
+
+TEST_F(TokenAnnotatorTest, UnderstandsVariableTemplates) {
+  auto Tokens =
+  annotate("template  "
+   "inline bool var = is_integral_v && is_signed_v;");
+  EXPECT_EQ(Tokens.size(), 20u) << Tokens;
+  EXPECT_TOKEN(Tokens[13], tok::ampamp, TT_BinaryOperator);
+}
+
 TEST_F(TokenAnnotatorTest, UnderstandsLBracesInMacroDefinition) {
   auto Tokens = annotate("#define BEGIN NS {");
   EXPECT_EQ(Tokens.size(), 6u) << Tokens;
@@ -164,17 +189,17 @@ TEST_F(TokenAnnotatorTest, 
UnderstandsFunctionRefQualifiers) {
   EXPECT_EQ(Tokens.size(), 7u) << Tokens;
   EXPECT_TOKEN(Tokens[4], tok::amp, TT_PointerOrReference);
 
-  Tokens = annotate("void operator=() &&;");
-  EXPECT_EQ(Tokens.size(), 8u) << Tokens;
-  EXPECT_TOKEN(Tokens[5], tok::ampamp, TT_PointerOrReference);
+  Tokens = annotate("void operator=(T) &&;");
+  EXPECT_EQ(Tokens.size(), 9u) << Tokens;
+  EXPECT_TOKEN(Tokens[6], tok::ampamp, TT_PointerOrReference);
 
   Tokens = annotate("templa

[clang] dbefb7e - [clang-format] Reformat. NFC.

2022-03-16 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-03-16T21:54:11+01:00
New Revision: dbefb7e86f82dcb1302b3d5559f733427d464a87

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

LOG: [clang-format] Reformat. NFC.

Added: 


Modified: 
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 926bf8905c7a6..8ee6040cd0f69 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -9919,10 +9919,13 @@ TEST_F(FormatTest, UnderstandsFunctionRefQualification) 
{
AlignLeft);
   verifyFormat("template  void operator=(T) &;", AlignLeft);
   verifyFormat("template  void operator=(T) const&;", AlignLeft);
-  verifyFormat("template  void operator=(T) & noexcept;", 
AlignLeft);
-  verifyFormat("template  void operator=(T) & = default;", 
AlignLeft);
+  verifyFormat("template  void operator=(T) & noexcept;",
+   AlignLeft);
+  verifyFormat("template  void operator=(T) & = default;",
+   AlignLeft);
   verifyFormat("template  void operator=(T) &&;", AlignLeft);
-  verifyFormat("template  void operator=(T) && = delete;", 
AlignLeft);
+  verifyFormat("template  void operator=(T) && = delete;",
+   AlignLeft);
   verifyFormat("template  void operator=(T) & {}", AlignLeft);
   verifyFormat("template  void operator=(T) && {}", AlignLeft);
 
@@ -9948,10 +9951,13 @@ TEST_F(FormatTest, UnderstandsFunctionRefQualification) 
{
AlignMiddle);
   verifyFormat("template  void operator=(T) &;", AlignMiddle);
   verifyFormat("template  void operator=(T) const &;", 
AlignMiddle);
-  verifyFormat("template  void operator=(T) & noexcept;", 
AlignMiddle);
-  verifyFormat("template  void operator=(T) & = default;", 
AlignMiddle);
+  verifyFormat("template  void operator=(T) & noexcept;",
+   AlignMiddle);
+  verifyFormat("template  void operator=(T) & = default;",
+   AlignMiddle);
   verifyFormat("template  void operator=(T) &&;", AlignMiddle);
-  verifyFormat("template  void operator=(T) && = delete;", 
AlignMiddle);
+  verifyFormat("template  void operator=(T) && = delete;",
+   AlignMiddle);
   verifyFormat("template  void operator=(T) & {}", AlignMiddle);
   verifyFormat("template  void operator=(T) && {}", AlignMiddle);
 



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


[clang] 34ce42f - [clang-format] Reformat. NFC.

2022-03-17 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-03-17T09:27:31+01:00
New Revision: 34ce42fe4de5318176e13e4cb758dfa7a0d8176b

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

LOG: [clang-format] Reformat. NFC.

Added: 


Modified: 
clang/lib/Format/WhitespaceManager.cpp
clang/unittests/Format/FormatTest.cpp
clang/unittests/Format/FormatTestJson.cpp
clang/unittests/Format/MacroExpanderTest.cpp
clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
clang/unittests/Format/TestLexer.h

Removed: 




diff  --git a/clang/lib/Format/WhitespaceManager.cpp 
b/clang/lib/Format/WhitespaceManager.cpp
index de6cdf4afd729..2dcc4fd62c5e8 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -1163,9 +1163,8 @@ void 
WhitespaceManager::alignArrayInitializersLeftJustified(
 auto Offset = std::distance(Cells.begin(), CellIter);
 for (const auto *Next = CellIter->NextColumnElement; Next != nullptr;
  Next = Next->NextColumnElement) {
-  if (RowCount > CellDescs.CellCounts.size()) {
+  if (RowCount > CellDescs.CellCounts.size())
 break;
-  }
   auto *Start = (Cells.begin() + RowCount * CellDescs.CellCounts[0]);
   auto *End = Start + Offset;
   auto ThisNetWidth = getNetWidth(Start, End, CellDescs.InitialSpaces);

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 8ee6040cd0f69..469252a252887 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -7217,9 +7217,8 @@ TEST_F(FormatTest, MemoizationTests) {
   OnePerLine.BinPackParameters = false;
   std::string input = "Constructor()\n"
   ": (a,\n";
-  for (unsigned i = 0, e = 80; i != e; ++i) {
+  for (unsigned i = 0, e = 80; i != e; ++i)
 input += "   a,\n";
-  }
   input += "   a) {}";
   verifyFormat(input, OnePerLine);
 }

diff  --git a/clang/unittests/Format/FormatTestJson.cpp 
b/clang/unittests/Format/FormatTestJson.cpp
index 14a48182f9dfe..e213f6bcbe712 100644
--- a/clang/unittests/Format/FormatTestJson.cpp
+++ b/clang/unittests/Format/FormatTestJson.cpp
@@ -30,14 +30,12 @@ class FormatTestJson : public ::testing::Test {
 if (Style.isJson() && !Style.DisableFormat) {
   auto Err = Replaces.add(
   tooling::Replacement(tooling::Replacement("", 0, 0, "x = ")));
-  if (Err) {
+  if (Err)
 llvm::errs() << "Bad Json variable insertion\n";
-  }
 }
 auto ChangedCode = applyAllReplacements(Code, Replaces);
-if (!ChangedCode) {
+if (!ChangedCode)
   llvm::errs() << "Bad Json varibale replacement\n";
-}
 StringRef NewCode = *ChangedCode;
 
 std::vector Ranges(1, tooling::Range(0, NewCode.size()));

diff  --git a/clang/unittests/Format/MacroExpanderTest.cpp 
b/clang/unittests/Format/MacroExpanderTest.cpp
index 7ec98a5e82b7b..37fa8d1cfc179 100644
--- a/clang/unittests/Format/MacroExpanderTest.cpp
+++ b/clang/unittests/Format/MacroExpanderTest.cpp
@@ -28,9 +28,8 @@ class MacroExpanderTest : public ::testing::Test {
   llvm::SmallVector
   lexArgs(const std::vector &Args) {
 llvm::SmallVector Result;
-for (const auto &Arg : Args) {
+for (const auto &Arg : Args)
   Result.push_back(uneof(Lex.lex(Arg)));
-}
 return Result;
   }
 
@@ -78,9 +77,8 @@ class MacroExpanderTest : public ::testing::Test {
 TEST_F(MacroExpanderTest, SkipsDefinitionOnError) {
   auto Macros =
   create({"A(", "B(,", "C(a,", "D(a a", "E(a, a", "F(,)", "G(a;"});
-  for (const auto *Name : {"A", "B", "C", "D", "E", "F", "G"}) {
+  for (const auto *Name : {"A", "B", "C", "D", "E", "F", "G"})
 EXPECT_FALSE(Macros->defined(Name)) << "for Name " << Name;
-  }
 }
 
 TEST_F(MacroExpanderTest, ExpandsWithoutArguments) {

diff  --git a/clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp 
b/clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
index 50b861fea1daf..342fdd3418098 100644
--- a/clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
+++ b/clang/unittests/Format/NamespaceEndCommentsFixerTest.cpp
@@ -469,7 +469,8 @@ TEST_F(NamespaceEndCommentsFixerTest, WorksForObjCpp) {
 fixNamespaceEndComments("namespace {\n"
 "int i;\n"
 "int j;\n"
-"}", ObjCppStyle));
+"}",
+ObjCppStyle));
 }
 
 TEST_F(NamespaceEndCommentsFixerTest, AddsMacroEndComment) {

diff  --git a/clang/unittests/Format/TestLexer.h 
b/clang/unittests/Format/TestLexer.h
index ae9818d7561b8..a1585fc5cac6d 100644
--- a/clang/unittests/Format/TestLexer.h
+++ b/clang/unittests/Format/TestLexer.h
@@ -37

[clang] dc142ea - [clang-format] Correctly recognize binary operators in template arguments with parenthesized literals.

2022-03-17 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-03-17T09:36:25+01:00
New Revision: dc142ea184a526fb2879f84c4c82fff195d36b9d

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

LOG: [clang-format] Correctly recognize binary operators in template arguments 
with parenthesized literals.

Fixes https://github.com/llvm/llvm-project/issues/24602.

Before, code like `foo` was formatted correctly but `foo` 
wasn't.
This patch fixes this inconsistency.

Reviewed By: HazardyKnusperkeks, owenpan

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index f1ff1995c806d..9c94590dc0b9a 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2177,14 +2177,21 @@ class AnnotatingParser {
 
 if (PrevToken->Tok.isLiteral() ||
 PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::kw_true,
-   tok::kw_false, tok::r_brace) ||
-NextToken->Tok.isLiteral() ||
-NextToken->isOneOf(tok::kw_true, tok::kw_false) ||
-NextToken->isUnaryOperator() ||
-// If we know we're in a template argument, there are no named
-// declarations. Thus, having an identifier on the right-hand side
-// indicates a binary operator.
-(InTemplateArgument && NextToken->Tok.isAnyIdentifier()))
+   tok::kw_false, tok::r_brace))
+  return TT_BinaryOperator;
+
+const FormatToken *NextNonParen = NextToken;
+while (NextNonParen && NextNonParen->is(tok::l_paren))
+  NextNonParen = NextNonParen->getNextNonComment();
+if (NextNonParen && (NextNonParen->Tok.isLiteral() ||
+ NextNonParen->isOneOf(tok::kw_true, tok::kw_false) ||
+ NextNonParen->isUnaryOperator()))
+  return TT_BinaryOperator;
+
+// If we know we're in a template argument, there are no named 
declarations.
+// Thus, having an identifier on the right-hand side indicates a binary
+// operator.
+if (InTemplateArgument && NextToken->Tok.isAnyIdentifier())
   return TT_BinaryOperator;
 
 // "&&(" is quite unlikely to be two successive unary "&".
@@ -4508,12 +4515,11 @@ bool TokenAnnotator::canBreakBefore(const AnnotatedLine 
&Line,
 
   // We only break before r_paren if we're in a block indented context.
   if (Right.is(tok::r_paren)) {
-if (Style.AlignAfterOpenBracket == FormatStyle::BAS_BlockIndent) {
+if (Style.AlignAfterOpenBracket == FormatStyle::BAS_BlockIndent)
   return Right.MatchingParen &&
  !(Right.MatchingParen->Previous &&
(Right.MatchingParen->Previous->is(tok::kw_for) ||
 Right.MatchingParen->Previous->isIf()));
-}
 
 return false;
   }

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 469252a252887..4ef4c9a8612a7 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -10333,6 +10333,11 @@ TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
   verifyFormat("vector v;");
   verifyFormat("foo();");
   verifyFormat("foo();");
+  verifyFormat("foo();");
+  verifyFormat("foo();");
+  verifyFormat("foo();");
+  verifyFormat("foo();");
+  verifyFormat("foo();");
   verifyFormat("decltype(*::std::declval()) void F();");
   verifyFormat("typeof(*::std::declval()) void F();");
   verifyFormat("_Atomic(*::std::declval()) void F();");



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


[clang] 45cb2df - [clang-format][docs] Regenerate ClangFormatStyleOptions.rst

2022-03-17 Thread Marek Kurdej via cfe-commits

Author: Krystian Kuzniarek
Date: 2022-03-17T09:45:43+01:00
New Revision: 45cb2df6788ca96a2ed6e9638b803563f51466f2

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

LOG: [clang-format][docs] Regenerate ClangFormatStyleOptions.rst

Misalignment of clang/docs/ClangFormatStyleOptions.rst and
clang/include/clang/Format/Format.h was introduced in c24b3db45.

Regenerated with:
python clang/docs/tools/dump_format_style.py

Reviewed By: sstwcw, curdeius, HazardyKnusperkeks

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

Added: 


Modified: 
clang/docs/ClangFormatStyleOptions.rst

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index a9e35fdceb810..543e7bbf410a3 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -358,8 +358,8 @@ the configuration (without a prefix: ``Auto``).
   /* A comment. */
   double e = 4;
 
-  * ``bool AlignCompound`` Only for ``AlignConsecutiveAssignments``.  Whether 
compound
-assignments like ``+=`` are aligned along with ``=``.
+  * ``bool AlignCompound`` Only for ``AlignConsecutiveAssignments``.  Whether 
compound assignments
+like ``+=`` are aligned along with ``=``.
 
 .. code-block:: c++
 
@@ -371,10 +371,9 @@ the configuration (without a prefix: ``Auto``).
   a &= 2;
   bbb = 2;
 
-  * ``bool PadOperators`` Only for ``AlignConsecutiveAssignments``.  Whether 
short
-assignment operators are left-padded to the same length as long
-ones in order to put all assignment operators to the right of
-the left hand side.
+  * ``bool PadOperators`` Only for ``AlignConsecutiveAssignments``.  Whether 
short assignment
+operators are left-padded to the same length as long ones in order to
+put all assignment operators to the right of the left hand side.
 
 .. code-block:: c++
 
@@ -482,8 +481,8 @@ the configuration (without a prefix: ``Auto``).
   /* A comment. */
   double e = 4;
 
-  * ``bool AlignCompound`` Only for ``AlignConsecutiveAssignments``.  Whether 
compound
-assignments like ``+=`` are aligned along with ``=``.
+  * ``bool AlignCompound`` Only for ``AlignConsecutiveAssignments``.  Whether 
compound assignments
+like ``+=`` are aligned along with ``=``.
 
 .. code-block:: c++
 
@@ -495,10 +494,9 @@ the configuration (without a prefix: ``Auto``).
   a &= 2;
   bbb = 2;
 
-  * ``bool PadOperators`` Only for ``AlignConsecutiveAssignments``.  Whether 
short
-assignment operators are left-padded to the same length as long
-ones in order to put all assignment operators to the right of
-the left hand side.
+  * ``bool PadOperators`` Only for ``AlignConsecutiveAssignments``.  Whether 
short assignment
+operators are left-padded to the same length as long ones in order to
+put all assignment operators to the right of the left hand side.
 
 .. code-block:: c++
 
@@ -606,8 +604,8 @@ the configuration (without a prefix: ``Auto``).
   /* A comment. */
   double e = 4;
 
-  * ``bool AlignCompound`` Only for ``AlignConsecutiveAssignments``.  Whether 
compound
-assignments like ``+=`` are aligned along with ``=``.
+  * ``bool AlignCompound`` Only for ``AlignConsecutiveAssignments``.  Whether 
compound assignments
+like ``+=`` are aligned along with ``=``.
 
 .. code-block:: c++
 
@@ -619,10 +617,9 @@ the configuration (without a prefix: ``Auto``).
   a &= 2;
   bbb = 2;
 
-  * ``bool PadOperators`` Only for ``AlignConsecutiveAssignments``.  Whether 
short
-assignment operators are left-padded to the same length as long
-ones in order to put all assignment operators to the right of
-the left hand side.
+  * ``bool PadOperators`` Only for ``AlignConsecutiveAssignments``.  Whether 
short assignment
+operators are left-padded to the same length as long ones in order to
+put all assignment operators to the right of the left hand side.
 
 .. code-block:: c++
 
@@ -731,8 +728,8 @@ the configuration (without a prefix: ``Auto``).
   /* A comment. */
   double e = 4;
 
-  * ``bool AlignCompound`` Only for ``AlignConsecutiveAssignments``.  Whether 
compound
-assignments like ``+=`` are aligned along with ``=``.
+  * ``bool AlignCompound`` Only for ``AlignConsecutiveAssignments``.  Whether 
compound assignments
+like ``+=`` are aligned along with ``=``.
 
 .. code-block:: c++
 
@@ -744,10 +741,9 @@ the configuration (without a prefix: ``Auto``).
   a &= 2;
   bbb = 2;
 
-  * ``bool PadOperators`` Only for ``AlignConsecutiveAssignments``.  Whether 
short
-assignment operators are left-padded to the same length as long
-ones in order to put all assignment operators to the right of

[clang] b6baab6 - [clang-format] Refactor BreakableBlockComment constructor. NFC.

2022-03-18 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-03-18T15:01:40+01:00
New Revision: b6baab673a7c17747c245fa7b33d9b29ad9a107d

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

LOG: [clang-format] Refactor BreakableBlockComment constructor. NFC.

Added: 


Modified: 
clang/lib/Format/BreakableToken.cpp

Removed: 




diff  --git a/clang/lib/Format/BreakableToken.cpp 
b/clang/lib/Format/BreakableToken.cpp
index ae084e9e14544..db7361bf5f2ff 100644
--- a/clang/lib/Format/BreakableToken.cpp
+++ b/clang/lib/Format/BreakableToken.cpp
@@ -410,11 +410,13 @@ BreakableBlockComment::BreakableBlockComment(
   }
   for (size_t i = 1, e = Content.size(); i < e && !Decoration.empty(); ++i) {
 const StringRef &Text = Content[i];
-// If the last line is empty, the closing "*/" will have a star.
-if (i + 1 == e && Text.empty())
-  break;
-if (!Text.empty() && i + 1 != e && Decoration.startswith(Text))
+if (i + 1 == e) {
+  // If the last line is empty, the closing "*/" will have a star.
+  if (Text.empty())
+break;
+} else if (!Text.empty() && Decoration.startswith(Text)) {
   continue;
+}
 while (!Text.startswith(Decoration))
   Decoration = Decoration.drop_back(1);
   }



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


[clang] acc7a7f - [clang-format] Use range-for loop. NFC.

2022-03-18 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-03-18T15:01:41+01:00
New Revision: acc7a7f9a17f683b1bbf0a4913ebadb926e1f71b

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

LOG: [clang-format] Use range-for loop. NFC.

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 9c94590dc0b9a..b0d48c46340a6 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -4601,8 +4601,8 @@ void TokenAnnotator::printDebugInfo(const AnnotatedLine 
&Line) {
  << " BK=" << Tok->getBlockKind() << " P=" << Tok->SplitPenalty
  << " Name=" << Tok->Tok.getName() << " L=" << Tok->TotalLength
  << " PPK=" << Tok->getPackingKind() << " FakeLParens=";
-for (unsigned i = 0, e = Tok->FakeLParens.size(); i != e; ++i)
-  llvm::errs() << Tok->FakeLParens[i] << "/";
+for (prec::Level LParen : Tok->FakeLParens)
+  llvm::errs() << LParen << "/";
 llvm::errs() << " FakeRParens=" << Tok->FakeRParens;
 llvm::errs() << " II=" << Tok->Tok.getIdentifierInfo();
 llvm::errs() << " Text='" << Tok->TokenText << "'\n";



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


[clang] c79e18d - [clang-format] Expect instead of setting the same value in tests. NFC.

2022-03-18 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-03-18T15:01:41+01:00
New Revision: c79e18da4f65c43bb8d94e95961e87e66d67b65a

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

LOG: [clang-format] Expect instead of setting the same value in tests. NFC.

Added: 


Modified: 
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 4ef4c9a8612a7..e36a267c01f4b 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -2767,7 +2767,8 @@ TEST_F(FormatTest, CaseRanges) {
 
 TEST_F(FormatTest, ShortEnums) {
   FormatStyle Style = getLLVMStyle();
-  Style.AllowShortEnumsOnASingleLine = true;
+  EXPECT_TRUE(Style.AllowShortEnumsOnASingleLine);
+  EXPECT_FALSE(Style.BraceWrapping.AfterEnum);
   verifyFormat("enum { A, B, C } ShortEnum1, ShortEnum2;", Style);
   verifyFormat("typedef enum { A, B, C } ShortEnum1, ShortEnum2;", Style);
   Style.AllowShortEnumsOnASingleLine = false;



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


[clang] c59c2b6 - [clang-format] Refactor ShouldBreakBeforeBrace to use switch. NFC.

2022-03-18 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-03-18T15:16:01+01:00
New Revision: c59c2b6bd19eb7625f7c234eb68d347d8de17079

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

LOG: [clang-format] Refactor ShouldBreakBeforeBrace to use switch. NFC.

Added: 


Modified: 
clang/lib/Format/UnwrappedLineParser.cpp

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index cadf1960dbf7a..bef8ed54fab8a 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -897,17 +897,24 @@ static bool isIIFE(const UnwrappedLine &Line,
 
 static bool ShouldBreakBeforeBrace(const FormatStyle &Style,
const FormatToken &InitialToken) {
-  if (InitialToken.isOneOf(tok::kw_namespace, TT_NamespaceMacro))
+  tok::TokenKind Kind = InitialToken.Tok.getKind();
+  if (InitialToken.is(TT_NamespaceMacro))
+Kind = tok::kw_namespace;
+
+  switch (Kind) {
+  case tok::kw_namespace:
 return Style.BraceWrapping.AfterNamespace;
-  if (InitialToken.is(tok::kw_class))
+  case tok::kw_class:
 return Style.BraceWrapping.AfterClass;
-  if (InitialToken.is(tok::kw_union))
+  case tok::kw_union:
 return Style.BraceWrapping.AfterUnion;
-  if (InitialToken.is(tok::kw_struct))
+  case tok::kw_struct:
 return Style.BraceWrapping.AfterStruct;
-  if (InitialToken.is(tok::kw_enum))
+  case tok::kw_enum:
 return Style.BraceWrapping.AfterEnum;
-  return false;
+  default:
+return false;
+  }
 }
 
 void UnwrappedLineParser::parseChildBlock(



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


[clang] 9dad527 - [clang-format] Use range-for loop with drop_end. NFC.

2022-03-21 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-03-21T10:05:06+01:00
New Revision: 9dad527fc048e9f6df6783abb1d6251e77f12199

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

LOG: [clang-format] Use range-for loop with drop_end. NFC.

Added: 


Modified: 
clang/lib/Format/ContinuationIndenter.cpp

Removed: 




diff  --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index 69508c44dc436..e3d54a0ba42a4 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -954,8 +954,8 @@ unsigned ContinuationIndenter::addTokenOnNewLine(LineState 
&State,
   (Current.MatchingParen &&
Current.MatchingParen->is(TT_RequiresExpressionLBrace));
   if (!NestedBlockSpecialCase)
-for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i)
-  State.Stack[i].BreakBeforeParameter = true;
+for (ParenState &PState : llvm::drop_end(State.Stack))
+  PState.BreakBeforeParameter = true;
 
   if (PreviousNonComment &&
   !PreviousNonComment->isOneOf(tok::comma, tok::colon, tok::semi) &&
@@ -1340,8 +1340,8 @@ unsigned 
ContinuationIndenter::moveStateToNextToken(LineState &State,
   !Previous->is(TT_DictLiteral) && State.Stack.size() > 1 &&
   !CurrentState.HasMultipleNestedBlocks) {
 if (State.Stack[State.Stack.size() - 2].NestedBlockInlined && Newline)
-  for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i)
-State.Stack[i].NoLineBreak = true;
+  for (ParenState &PState : llvm::drop_end(State.Stack))
+PState.NoLineBreak = true;
 State.Stack[State.Stack.size() - 2].NestedBlockInlined = false;
   }
   if (Previous && (Previous->isOneOf(TT_BinaryOperator, TT_ConditionalExpr) ||



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


[clang] 73a15ad - [clang-format] [doc] Improve BraceWrapping documentation.

2022-03-21 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-03-21T10:25:12+01:00
New Revision: 73a15ad567071c13e761fd6d593e2b66164865e2

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

LOG: [clang-format] [doc] Improve BraceWrapping documentation.

Added: 


Modified: 
clang/include/clang/Format/Format.h

Removed: 




diff  --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index eb53d7987dbd2..d815eb1165bb3 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -1592,6 +1592,7 @@ struct FormatStyle {
 /// set, and the function could/should not be put on a single line (as per
 /// `AllowShortFunctionsOnASingleLine` and constructor formatting options).
 /// \code
+///   false:  true:
 ///   int f()   vs.   int f()
 ///   {}  {
 ///   }
@@ -1603,6 +1604,7 @@ struct FormatStyle {
 /// brace of the record has already been wrapped, i.e. the `AfterClass`
 /// (for classes) brace wrapping mode is set.
 /// \code
+///   false:   true:
 ///   class Foo   vs.  class Foo
 ///   {}   {
 ///}
@@ -1614,6 +1616,7 @@ struct FormatStyle {
 /// already been wrapped, i.e. the `AfterNamespace` brace wrapping mode is
 /// set.
 /// \code
+///   false:   true:
 ///   namespace Foo   vs.  namespace Foo
 ///   {}   {
 ///}



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


[clang] a45ad3c - [clang-format] [doc] Add script to automatically update help output in ClangFormat.rst.

2022-03-23 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-03-23T13:17:50+01:00
New Revision: a45ad3ca8ce78988a4d51b432455ce0bbf13

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

LOG: [clang-format] [doc] Add script to automatically update help output in 
ClangFormat.rst.

Fixes https://github.com/llvm/llvm-project/issues/54418.

Reviewed By: MyDeveloperDay

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

Added: 
clang/docs/tools/dump_format_help.py

Modified: 
clang/docs/ClangFormat.rst
clang/tools/clang-format/ClangFormat.cpp

Removed: 




diff  --git a/clang/docs/ClangFormat.rst b/clang/docs/ClangFormat.rst
index 5fc9656a4756a..745c66efa9e0e 100644
--- a/clang/docs/ClangFormat.rst
+++ b/clang/docs/ClangFormat.rst
@@ -13,6 +13,8 @@ Standalone Tool
 :program:`clang-format` is located in `clang/tools/clang-format` and can be 
used
 to format C/C++/Java/JavaScript/JSON/Objective-C/Protobuf/C# code.
 
+.. START_FORMAT_HELP
+
 .. code-block:: console
 
   $ clang-format -help
@@ -51,7 +53,9 @@ to format C/C++/Java/JavaScript/JSON/Objective-C/Protobuf/C# 
code.
  -style=file, but can not find the 
.clang-format
  file to use.
  Use -fallback-style=none to skip 
formatting.
---ferror-limit=  - Set the maximum number of clang-format 
errors to emit before stopping (0 = no limit). Used only with --dry-run or -n
+--ferror-limit=  - Set the maximum number of clang-format 
errors to emit
+ before stopping (0 = no limit).
+ Used only with --dry-run or -n
 --files=   - Provide a list of files to run 
clang-format
 -i - Inplace edit s, if specified.
 --length=- Format a range of this length (in bytes).
@@ -73,8 +77,10 @@ to format C/C++/Java/JavaScript/JSON/Objective-C/Protobuf/C# 
code.
  several -offset and -length pairs.
  Can only be used with one input file.
 --output-replacements-xml  - Output replacements as XML.
---qualifier-alignment= - If set, overrides the qualifier alignment 
style determined by the QualifierAlignment style flag
---sort-includes- If set, overrides the include sorting 
behavior determined by the SortIncludes style flag
+--qualifier-alignment= - If set, overrides the qualifier alignment 
style
+ determined by the QualifierAlignment 
style flag
+--sort-includes- If set, overrides the include sorting 
behavior
+ determined by the SortIncludes style flag
 --style=   - Coding style, currently supports:
LLVM, GNU, Google, Chromium, Microsoft, 
Mozilla, WebKit.
  Use -style=file to load style 
configuration from
@@ -95,6 +101,8 @@ to format C/C++/Java/JavaScript/JSON/Objective-C/Protobuf/C# 
code.
 --version  - Display the version of this program
 
 
+.. END_FORMAT_HELP
+
 When the desired code formatting style is 
diff erent from the available options,
 the style can be customized using the ``-style="{key: value, ...}"`` option or
 by putting your style configuration in the ``.clang-format`` or 
``_clang-format``

diff  --git a/clang/docs/tools/dump_format_help.py 
b/clang/docs/tools/dump_format_help.py
new file mode 100644
index 0..68869d91056ce
--- /dev/null
+++ b/clang/docs/tools/dump_format_help.py
@@ -0,0 +1,64 @@
+#!/usr/bin/env python3
+# A tool to parse the output of `clang-format --help` and update the
+# documentation in ../ClangFormat.rst automatically.
+
+import os
+import re
+import subprocess
+import sys
+
+CLANG_DIR = os.path.join(os.path.dirname(__file__), '../..')
+DOC_FILE = os.path.join(CLANG_DIR, 'docs/ClangFormat.rst')
+
+
+def substitute(text, tag, contents):
+replacement = '\n.. START_%s\n\n%s\n\n.. END_%s\n' % (tag, contents, tag)
+pattern = r'\n\.\. START_%s\n.*\n\.\. END_%s\n' % (tag, tag)
+return re.sub(pattern, '%s', text, flags=re.S) % replacement
+
+
+def indent(text, columns, indent_first_line=True):
+indent_str = ' ' * columns
+s = re.sub(r'\n([^\n])', '\n' + indent_str + '\\1', text, flags=re.S)
+if not indent_first_line or s.startswith('\n'):
+return s
+return indent_str + s
+
+
+def get_help_output():
+args = ["clang-format", "--help"]
+cmd = subprocess.Popen(args, stdout=subprocess.PIPE,
+   stderr=subprocess.STDOUT)
+out, _ = cmd.communicate()
+out = out.decode(sys.stdout.enco

[clang] 4e88cb6 - [clang-format] Handle attributes before case label. Relanded.

2022-03-23 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-03-23T16:24:24+01:00
New Revision: 4e88cb6825eefca3c0eb66b5ae40ab123fcc7073

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

LOG: [clang-format] Handle attributes before case label. Relanded.

Fixes https://github.com/llvm/llvm-project/issues/53110.

Reviewed By: MyDeveloperDay, HazardyKnusperkeks, owenpan

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

Relanding as the original patch provoked an infinite loop in 
JavaScript/TypeScript.
A reproducer test case was added and the issue fixed.

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 36205b8ee18cd..8052eb932141d 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -480,6 +480,10 @@ bool UnwrappedLineParser::parseLevel(bool HasOpeningBrace,
   unsigned StatementCount = 0;
   bool SwitchLabelEncountered = false;
   do {
+if (FormatTok->getType() == TT_AttributeMacro) {
+  nextToken();
+  continue;
+}
 tok::TokenKind kind = FormatTok->Tok.getKind();
 if (FormatTok->getType() == TT_MacroBlockBegin)
   kind = tok::l_brace;
@@ -569,6 +573,8 @@ bool UnwrappedLineParser::parseLevel(bool HasOpeningBrace,
 parseCSharpAttribute();
 break;
   }
+  if (handleCppAttributes())
+break;
   LLVM_FALLTHROUGH;
 default:
   ParseDefault();
@@ -1397,9 +1403,11 @@ void 
UnwrappedLineParser::parseStructuralElement(IfStmtKind *IfKind,
 // e.g. "default void f() {}" in a Java interface.
 break;
   case tok::kw_case:
-if (Style.isJavaScript() && Line->MustBeDeclaration)
+if (Style.isJavaScript() && Line->MustBeDeclaration) {
   // 'case: string' field declaration.
+  nextToken();
   break;
+}
 parseCaseLabel();
 return;
   case tok::kw_try:
@@ -1820,6 +1828,14 @@ void 
UnwrappedLineParser::parseStructuralElement(IfStmtKind *IfKind,
 case tok::kw_new:
   parseNew();
   break;
+case tok::kw_case:
+  if (Style.isJavaScript() && Line->MustBeDeclaration) {
+// 'case: string' field declaration.
+nextToken();
+break;
+  }
+  parseCaseLabel();
+  break;
 default:
   nextToken();
   break;
@@ -2388,17 +2404,24 @@ static void markOptionalBraces(FormatToken *LeftBrace) {
   RightBrace->Optional = true;
 }
 
+void UnwrappedLineParser::handleAttributes() {
+  // Handle AttributeMacro, e.g. `if (x) UNLIKELY`.
+  if (FormatTok->is(TT_AttributeMacro))
+nextToken();
+  handleCppAttributes();
+}
+
+bool UnwrappedLineParser::handleCppAttributes() {
+  // Handle [[likely]] / [[unlikely]] attributes.
+  if (FormatTok->is(tok::l_square) && tryToParseSimpleAttribute()) {
+parseSquare();
+return true;
+  }
+  return false;
+}
+
 FormatToken *UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind,
   bool KeepBraces) {
-  auto HandleAttributes = [this]() {
-// Handle AttributeMacro, e.g. `if (x) UNLIKELY`.
-if (FormatTok->is(TT_AttributeMacro))
-  nextToken();
-// Handle [[likely]] / [[unlikely]] attributes.
-if (FormatTok->is(tok::l_square) && tryToParseSimpleAttribute())
-  parseSquare();
-  };
-
   assert(FormatTok->is(tok::kw_if) && "'if' expected");
   nextToken();
   if (FormatTok->is(tok::exclaim))
@@ -2411,7 +2434,7 @@ FormatToken 
*UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind,
 if (FormatTok->is(tok::l_paren))
   parseParens();
   }
-  HandleAttributes();
+  handleAttributes();
 
   bool NeedsUnwrappedLine = false;
   keepAncestorBraces();
@@ -2448,7 +2471,7 @@ FormatToken 
*UnwrappedLineParser::parseIfThenElse(IfStmtKind *IfKind,
   Kind = IfStmtKind::IfElse;
 }
 nextToken();
-HandleAttributes();
+handleAttributes();
 if (FormatTok->is(tok::l_brace)) {
   ElseLeftBrace = FormatTok;
   CompoundStatementIndenter Indenter(this, Style, Line->Level);

diff  --git a/clang/lib/Format/UnwrappedLineParser.h 
b/clang/lib/Format/UnwrappedLineParser.h
index 5cc01398a5457..798bae24ad075 100644
--- a/clang/lib/Format/UnwrappedLineParser.h
+++ b/clang/lib/Format/UnwrappedLineParser.h
@@ -121,6 +121,8 @@ class UnwrappedLineParser {
   void parseSquare(bool LambdaIntroducer = false);
   void keepAncestorBraces();
   void parseUnbracedBody(bool CheckEOF = false);
+  void handleAttributes();
+  bool handleCppAttributes();
   FormatToken *parseIfThenElse(IfStmtKind *IfKind, bool KeepBraces = false);
   void parseTryCatch();

[clang] b58616c - [clang-format] Fix SeparateDefinitionBlocks breaking up function-try-block.

2022-04-13 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-04-13T16:44:04+02:00
New Revision: b58616c2cdf70e075b887a66edf6bbc568e2ff99

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

LOG: [clang-format] Fix SeparateDefinitionBlocks breaking up function-try-block.

Fixes https://github.com/llvm/llvm-project/issues/54536.

Reviewed By: HazardyKnusperkeks, owenpan

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index c5594a6d66484..018a7ae3ee794 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -2603,6 +2603,7 @@ void UnwrappedLineParser::parseTryCatch() {
   nextToken();
 }
 NeedsUnwrappedLine = false;
+Line->MustBeDeclaration = false;
 CompoundStatementIndenter Indenter(this, Style, Line->Level);
 parseBlock();
 if (Style.BraceWrapping.BeforeCatch)

diff  --git a/clang/unittests/Format/DefinitionBlockSeparatorTest.cpp 
b/clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
index 53a3c57ad59fa..cb24cc921bc05 100644
--- a/clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
+++ b/clang/unittests/Format/DefinitionBlockSeparatorTest.cpp
@@ -43,7 +43,8 @@ class DefinitionBlockSeparatorTest : public ::testing::Test {
 
   static void _verifyFormat(const char *File, int Line, llvm::StringRef Code,
 const FormatStyle &Style = getLLVMStyle(),
-llvm::StringRef ExpectedCode = "") {
+llvm::StringRef ExpectedCode = "",
+bool Inverse = true) {
 ::testing::ScopedTrace t(File, Line, ::testing::Message() << Code.str());
 bool HasOriginalCode = true;
 if (ExpectedCode == "") {
@@ -51,16 +52,18 @@ class DefinitionBlockSeparatorTest : public ::testing::Test 
{
   HasOriginalCode = false;
 }
 
-FormatStyle InverseStyle = Style;
-if (Style.SeparateDefinitionBlocks == FormatStyle::SDS_Always)
-  InverseStyle.SeparateDefinitionBlocks = FormatStyle::SDS_Never;
-else
-  InverseStyle.SeparateDefinitionBlocks = FormatStyle::SDS_Always;
 EXPECT_EQ(ExpectedCode, separateDefinitionBlocks(ExpectedCode, Style))
 << "Expected code is not stable";
-EXPECT_NE(ExpectedCode,
-  separateDefinitionBlocks(ExpectedCode, InverseStyle))
-<< "Inverse formatting makes no 
diff erence";
+if (Inverse) {
+  FormatStyle InverseStyle = Style;
+  if (Style.SeparateDefinitionBlocks == FormatStyle::SDS_Always)
+InverseStyle.SeparateDefinitionBlocks = FormatStyle::SDS_Never;
+  else
+InverseStyle.SeparateDefinitionBlocks = FormatStyle::SDS_Always;
+  EXPECT_NE(ExpectedCode,
+separateDefinitionBlocks(ExpectedCode, InverseStyle))
+  << "Inverse formatting makes no 
diff erence";
+}
 std::string CodeToFormat =
 HasOriginalCode ? Code.str() : removeEmptyLines(Code);
 std::string Result = separateDefinitionBlocks(CodeToFormat, Style);
@@ -448,6 +451,32 @@ TEST_F(DefinitionBlockSeparatorTest, 
OpeningBracketOwnsLine) {
Style);
 }
 
+TEST_F(DefinitionBlockSeparatorTest, TryBlocks) {
+  FormatStyle Style = getLLVMStyle();
+  Style.BreakBeforeBraces = FormatStyle::BS_Allman;
+  Style.SeparateDefinitionBlocks = FormatStyle::SDS_Always;
+  verifyFormat("void FunctionWithInternalTry()\n"
+   "{\n"
+   "  try\n"
+   "  {\n"
+   "return;\n"
+   "  }\n"
+   "  catch (const std::exception &)\n"
+   "  {\n"
+   "  }\n"
+   "}",
+   Style, "", /*Inverse=*/false);
+  verifyFormat("void FunctionWithTryBlock()\n"
+   "try\n"
+   "{\n"
+   "  return;\n"
+   "}\n"
+   "catch (const std::exception &)\n"
+   "{\n"
+   "}",
+   Style, "", /*Inverse=*/false);
+}
+
 TEST_F(DefinitionBlockSeparatorTest, Leave) {
   FormatStyle Style = getLLVMStyle();
   Style.SeparateDefinitionBlocks = FormatStyle::SDS_Leave;



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


[clang] bb1b53d - [clang-format] Remove unnecessary non-null check and assert instead. NFC.

2022-02-03 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-02-03T09:50:36+01:00
New Revision: bb1b53da6eeb90d3c101719f569abce1d689a959

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

LOG: [clang-format] Remove unnecessary non-null check and assert instead. NFC.

After a non-eof token, there is at least an eof token.

Added: 


Modified: 
clang/lib/Format/UnwrappedLineParser.cpp

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 8d06277caba37..cdc2740ba9642 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -514,9 +514,10 @@ bool UnwrappedLineParser::parseLevel(bool HasOpeningBrace, 
IfStmtKind *IfKind) {
   FormatToken *Next;
   do {
 Next = Tokens->getNextToken();
+assert(Next);
   } while (Next->is(tok::comment));
   FormatTok = Tokens->setPosition(StoredPosition);
-  if (Next && Next->isNot(tok::colon)) {
+  if (Next->isNot(tok::colon)) {
 // default not followed by ':' is not a case label; treat it like
 // an identifier.
 parseStructuralElement();



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


[clang] 7cc3e02 - [clang-format] Use back() instead of rbegin(). NFC.

2022-02-03 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-02-03T10:07:02+01:00
New Revision: 7cc3e0204210a8c9c12f29fddbfec9dfe786e931

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

LOG: [clang-format] Use back() instead of rbegin(). NFC.

Added: 


Modified: 
clang/lib/Format/TokenAnalyzer.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnalyzer.cpp 
b/clang/lib/Format/TokenAnalyzer.cpp
index 2bd5a1fd6230..348da1f03f29 100644
--- a/clang/lib/Format/TokenAnalyzer.cpp
+++ b/clang/lib/Format/TokenAnalyzer.cpp
@@ -110,7 +110,7 @@ std::pair 
TokenAnalyzer::process() {
   UnwrappedLineParser Parser(Style, Lex.getKeywords(),
  Env.getFirstStartColumn(), Tokens, *this);
   Parser.parse();
-  assert(UnwrappedLines.rbegin()->empty());
+  assert(UnwrappedLines.back().empty());
   unsigned Penalty = 0;
   for (unsigned Run = 0, RunE = UnwrappedLines.size(); Run + 1 != RunE; ++Run) 
{
 const auto &Lines = UnwrappedLines[Run];



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


[clang] 768a619 - [clang-format] Reserve vectors when the number of items is known beforehand. NFC.

2022-02-03 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-02-03T10:38:23+01:00
New Revision: 768a6192dfc680c0c941e713c824b9046429538d

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

LOG: [clang-format] Reserve vectors when the number of items is known 
beforehand. NFC.

Added: 


Modified: 
clang/lib/Format/FormatToken.cpp
clang/lib/Format/TokenAnalyzer.cpp

Removed: 




diff  --git a/clang/lib/Format/FormatToken.cpp 
b/clang/lib/Format/FormatToken.cpp
index 59d6f29bb54d2..40aa8f5cacb25 100644
--- a/clang/lib/Format/FormatToken.cpp
+++ b/clang/lib/Format/FormatToken.cpp
@@ -186,6 +186,9 @@ void CommaSeparatedList::precomputeFormattingInfos(const 
FormatToken *Token) {
   // The lengths of an item if it is put at the end of the line. This includes
   // trailing comments which are otherwise ignored for column alignment.
   SmallVector EndOfLineItemLength;
+  MustBreakBeforeItem.reserve(Commas.size() + 1);
+  EndOfLineItemLength.reserve(Commas.size() + 1);
+  ItemLengths.reserve(Commas.size() + 1);
 
   bool HasSeparatingComment = false;
   for (unsigned i = 0, e = Commas.size() + 1; i != e; ++i) {

diff  --git a/clang/lib/Format/TokenAnalyzer.cpp 
b/clang/lib/Format/TokenAnalyzer.cpp
index 348da1f03f299..0a775c0a87eda 100644
--- a/clang/lib/Format/TokenAnalyzer.cpp
+++ b/clang/lib/Format/TokenAnalyzer.cpp
@@ -116,6 +116,7 @@ std::pair 
TokenAnalyzer::process() {
 const auto &Lines = UnwrappedLines[Run];
 LLVM_DEBUG(llvm::dbgs() << "Run " << Run << "...\n");
 SmallVector AnnotatedLines;
+AnnotatedLines.reserve(Lines.size());
 
 TokenAnnotator Annotator(Style, Lex.getKeywords());
 for (const UnwrappedLine &Line : Lines) {



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


[clang] 529aa4b - [clang-format] Avoid adding space after the name of a function-like macro when the name is a keyword.

2022-02-03 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-02-03T18:45:51+01:00
New Revision: 529aa4b011c4ae808d658022ef643c44dd9b2c9c

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

LOG: [clang-format] Avoid adding space after the name of a function-like macro 
when the name is a keyword.

Fixes https://github.com/llvm/llvm-project/issues/31086.

Before the code:
```
#define if(x)
```

was erroneously formatted to:
```
#define if (x)
```

Reviewed By: HazardyKnusperkeks, owenpan

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index c43c8da6f3984..37fad4d9f49de 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -1007,6 +1007,12 @@ void UnwrappedLineParser::parsePPDefine() {
 }
   }
 
+  // In the context of a define, even keywords should be treated as normal
+  // identifiers. Setting the kind to identifier is not enough, because we need
+  // to treat additional keywords like __except as well, which are already
+  // identifiers.
+  FormatTok->Tok.setKind(tok::identifier);
+  FormatTok->Tok.setIdentifierInfo(nullptr);
   nextToken();
   if (FormatTok->Tok.getKind() == tok::l_paren &&
   !FormatTok->hasWhitespaceBefore())

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 720c6e9b6b2f1..3d9e38616450c 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -1795,6 +1795,18 @@ TEST_F(FormatTest, FormatShortBracedStatements) {
AllowSimpleBracedStatements);
 }
 
+TEST_F(FormatTest, UnderstandsMacros) {
+  verifyFormat("#define A (parentheses)");
+  verifyFormat("#define true ((int)1)");
+  verifyFormat("#define and(x)");
+  verifyFormat("#define if(x) x");
+  verifyFormat("#define return(x) (x)");
+  verifyFormat("#define while(x) for (; x;)");
+  verifyFormat("#define xor(x) (^(x))");
+  verifyFormat("#define __except(x)");
+  verifyFormat("#define __try(x)");
+}
+
 TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) {
   FormatStyle Style = getLLVMStyleWithColumns(60);
   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;



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


[clang] ca0d970 - [clang-format] Avoid merging macro definitions.

2022-02-03 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-02-03T18:54:46+01:00
New Revision: ca0d97072e79f8d7159c50db616647eeb1b094b8

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

LOG: [clang-format] Avoid merging macro definitions.

Fixes https://github.com/llvm/llvm-project/issues/42087.

Reviewed By: HazardyKnusperkeks, owenpan

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineFormatter.cpp 
b/clang/lib/Format/UnwrappedLineFormatter.cpp
index 08ba442b5f0e..f7d26b813f4f 100644
--- a/clang/lib/Format/UnwrappedLineFormatter.cpp
+++ b/clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -621,6 +621,10 @@ class LineJoiner {
   tryMergeSimpleBlock(SmallVectorImpl::const_iterator I,
   SmallVectorImpl::const_iterator E,
   unsigned Limit) {
+// Don't merge with a preprocessor directive.
+if (I[1]->Type == LT_PreprocessorDirective)
+  return 0;
+
 AnnotatedLine &Line = **I;
 
 // Don't merge ObjC @ keywords and methods.

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 3d9e38616450..094b9142aa10 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -1805,6 +1805,21 @@ TEST_F(FormatTest, UnderstandsMacros) {
   verifyFormat("#define xor(x) (^(x))");
   verifyFormat("#define __except(x)");
   verifyFormat("#define __try(x)");
+
+  FormatStyle Style = getLLVMStyle();
+  Style.BreakBeforeBraces = FormatStyle::BS_Custom;
+  Style.BraceWrapping.AfterFunction = true;
+  // Test that a macro definition never gets merged with the following
+  // definition.
+  // FIXME: The AAA macro definition probably should not be split into 3 lines.
+  verifyFormat("#define AAA
"
+   "\\\n"
+   "  N
"
+   "\\\n"
+   "  {\n"
+   "#define BBB }\n",
+   Style);
+  // verifyFormat("#define AAA N { //\n", Style);
 }
 
 TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) {



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


[clang] 06e4259 - [clang-format] Comment unused parameters. NFC.

2022-02-08 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-02-08T09:33:55+01:00
New Revision: 06e42590a5275fb8f6f7f225968620b5efe5b6f5

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

LOG: [clang-format] Comment unused parameters. NFC.

Added: 


Modified: 
clang/lib/Format/QualifierAlignmentFixer.cpp

Removed: 




diff  --git a/clang/lib/Format/QualifierAlignmentFixer.cpp 
b/clang/lib/Format/QualifierAlignmentFixer.cpp
index 1a0f743a9cba..13af32a9f4f4 100644
--- a/clang/lib/Format/QualifierAlignmentFixer.cpp
+++ b/clang/lib/Format/QualifierAlignmentFixer.cpp
@@ -59,8 +59,9 @@ QualifierAlignmentFixer::QualifierAlignmentFixer(
 }
 
 std::pair QualifierAlignmentFixer::analyze(
-TokenAnnotator &Annotator, SmallVectorImpl 
&AnnotatedLines,
-FormatTokenLexer &Tokens) {
+TokenAnnotator & /*Annotator*/,
+SmallVectorImpl & /*AnnotatedLines*/,
+FormatTokenLexer & /*Tokens*/) {
   auto Env = Environment::make(Code, FileName, Ranges, FirstStartColumn,
NextStartColumn, LastStartColumn);
   if (!Env)
@@ -376,7 +377,8 @@ 
LeftRightQualifierAlignmentFixer::LeftRightQualifierAlignmentFixer(
 
 std::pair
 LeftRightQualifierAlignmentFixer::analyze(
-TokenAnnotator &Annotator, SmallVectorImpl 
&AnnotatedLines,
+TokenAnnotator & /*Annotator*/,
+SmallVectorImpl &AnnotatedLines,
 FormatTokenLexer &Tokens) {
   tooling::Replacements Fixes;
   const AdditionalKeywords &Keywords = Tokens.getKeywords();



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


[clang] 7d63973 - [clang-format] Fix typo. NFC.

2022-02-08 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-02-08T09:33:54+01:00
New Revision: 7d6397348e453a0c941bca0f3a30087680d2f14c

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

LOG: [clang-format] Fix typo. NFC.

Added: 


Modified: 
clang/lib/Format/QualifierAlignmentFixer.cpp

Removed: 




diff  --git a/clang/lib/Format/QualifierAlignmentFixer.cpp 
b/clang/lib/Format/QualifierAlignmentFixer.cpp
index aeec8da951827..1a0f743a9cbaf 100644
--- a/clang/lib/Format/QualifierAlignmentFixer.cpp
+++ b/clang/lib/Format/QualifierAlignmentFixer.cpp
@@ -37,7 +37,7 @@ QualifierAlignmentFixer::QualifierAlignmentFixer(
   PrepareLeftRightOrdering(Style.QualifierOrder, LeftOrder, RightOrder,
ConfiguredQualifierTokens);
 
-  // Handle the left and right Alignment Seperately
+  // Handle the left and right alignment separately.
   for (const auto &Qualifier : LeftOrder) {
 Passes.emplace_back(
 [&, Qualifier, ConfiguredQualifierTokens](const Environment &Env) {



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


[clang] e329b58 - [clang-format] Honour "// clang-format off" when using QualifierOrder.

2022-02-09 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-02-09T22:15:20+01:00
New Revision: e329b5866f1732f5c24cf2ae96479971f7101914

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

LOG: [clang-format] Honour "// clang-format off" when using QualifierOrder.

Fixes https://github.com/llvm/llvm-project/issues/53643.

Reviewed By: MyDeveloperDay, HazardyKnusperkeks, owenpan

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

Added: 


Modified: 
clang/lib/Format/QualifierAlignmentFixer.cpp
clang/unittests/Format/QualifierFixerTest.cpp

Removed: 




diff  --git a/clang/lib/Format/QualifierAlignmentFixer.cpp 
b/clang/lib/Format/QualifierAlignmentFixer.cpp
index 13af32a9f4f47..233b081a95f6d 100644
--- a/clang/lib/Format/QualifierAlignmentFixer.cpp
+++ b/clang/lib/Format/QualifierAlignmentFixer.cpp
@@ -390,6 +390,10 @@ LeftRightQualifierAlignmentFixer::analyze(
 
   for (AnnotatedLine *Line : AnnotatedLines) {
 FormatToken *First = Line->First;
+assert(First);
+if (First->Finalized)
+  continue;
+
 const auto *Last = Line->Last;
 
 for (const auto *Tok = First; Tok && Tok != Last && Tok->Next;

diff  --git a/clang/unittests/Format/QualifierFixerTest.cpp 
b/clang/unittests/Format/QualifierFixerTest.cpp
index 0517de2820d9d..14f09d875e6be 100755
--- a/clang/unittests/Format/QualifierFixerTest.cpp
+++ b/clang/unittests/Format/QualifierFixerTest.cpp
@@ -858,5 +858,27 @@ TEST_F(QualifierFixerTest, QualifierTemplates) {
Style);
 }
 
+TEST_F(QualifierFixerTest, DisableRegions) {
+  FormatStyle Style = getLLVMStyle();
+  Style.QualifierAlignment = FormatStyle::QAS_Custom;
+  Style.QualifierOrder = {"inline", "static", "const", "type"};
+
+  ReplacementCount = 0;
+  verifyFormat("// clang-format off\n"
+   "int const inline static a = 0;\n"
+   "// clang-format on\n",
+   Style);
+  EXPECT_EQ(ReplacementCount, 0);
+  verifyFormat("// clang-format off\n"
+   "int const inline static a = 0;\n"
+   "// clang-format on\n"
+   "inline static const int a = 0;\n",
+   "// clang-format off\n"
+   "int const inline static a = 0;\n"
+   "// clang-format on\n"
+   "int const inline static a = 0;\n",
+   Style);
+}
+
 } // namespace format
 } // namespace clang



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


[clang] a77c67f - [clang-format] Fix formatting of the array form of delete.

2022-02-09 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-02-09T22:36:13+01:00
New Revision: a77c67f93917596f9eded9edaced4a9d355a4e1c

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

LOG: [clang-format] Fix formatting of the array form of delete.

Fixes https://github.com/llvm/llvm-project/issues/53576.

There was an inconsistency in formatting of delete expressions.

Before:
```
delete (void*)a;
delete[](void*) a;
```

After this patch:
```
delete (void*)a;
delete[] (void*)a;
```

Reviewed By: HazardyKnusperkeks, owenpan

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 76f623147d3a4..28b244b9c59f1 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1883,6 +1883,25 @@ class AnnotatingParser {
 LeftOfParens = LeftOfParens->MatchingParen->Previous;
   }
 
+  if (LeftOfParens->is(tok::r_square)) {
+//   delete[] (void *)ptr;
+auto MayBeArrayDelete = [](FormatToken *Tok) -> FormatToken * {
+  if (Tok->isNot(tok::r_square))
+return nullptr;
+
+  Tok = Tok->getPreviousNonComment();
+  if (!Tok || Tok->isNot(tok::l_square))
+return nullptr;
+
+  Tok = Tok->getPreviousNonComment();
+  if (!Tok || Tok->isNot(tok::kw_delete))
+return nullptr;
+  return Tok;
+};
+if (FormatToken *MaybeDelete = MayBeArrayDelete(LeftOfParens))
+  LeftOfParens = MaybeDelete;
+  }
+
   // The Condition directly below this one will see the operator arguments
   // as a (void *foo) cast.
   //   void operator delete(void *foo) ATTRIB;
@@ -3227,7 +3246,10 @@ bool TokenAnnotator::spaceRequiredBetween(const 
AnnotatedLine &Line,
   if (Left.isOneOf(tok::kw_try, Keywords.kw___except, tok::kw_catch))
 return Style.SpaceBeforeParensOptions.AfterControlStatements ||
spaceRequiredBeforeParens(Right);
-  if (Left.isOneOf(tok::kw_new, tok::kw_delete))
+  if (Left.isOneOf(tok::kw_new, tok::kw_delete) ||
+  (Left.is(tok::r_square) && Left.MatchingParen &&
+   Left.MatchingParen->Previous &&
+   Left.MatchingParen->Previous->is(tok::kw_delete)))
 return Style.SpaceBeforeParens != FormatStyle::SBPO_Never ||
spaceRequiredBeforeParens(Right);
 }

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 14942d1ba420e..6f76a0c62edf9 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -9744,6 +9744,7 @@ TEST_F(FormatTest, UnderstandsNewAndDelete) {
"new 
(aa(aaa))\n"
"typename ();");
   verifyFormat("delete[] h->p;");
+  verifyFormat("delete[] (void *)p;");
 
   verifyFormat("void operator delete(void *foo) ATTRIB;");
   verifyFormat("void operator new(void *foo) ATTRIB;");

diff  --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 88deee974bbf5..acb7386a89df9 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -97,6 +97,28 @@ TEST_F(TokenAnnotatorTest, 
UnderstandsLBracesInMacroDefinition) {
   EXPECT_TOKEN(Tokens[4], tok::l_brace, TT_Unknown);
 }
 
+TEST_F(TokenAnnotatorTest, UnderstandsDelete) {
+  auto Tokens = annotate("delete (void *)p;");
+  EXPECT_EQ(Tokens.size(), 8u) << Tokens;
+  EXPECT_TOKEN(Tokens[4], tok::r_paren, TT_CastRParen);
+
+  Tokens = annotate("delete[] (void *)p;");
+  EXPECT_EQ(Tokens.size(), 10u) << Tokens;
+  EXPECT_TOKEN(Tokens[6], tok::r_paren, TT_CastRParen);
+
+  Tokens = annotate("delete[] /*comment*/ (void *)p;");
+  EXPECT_EQ(Tokens.size(), 11u) << Tokens;
+  EXPECT_TOKEN(Tokens[7], tok::r_paren, TT_CastRParen);
+
+  Tokens = annotate("delete[/*comment*/] (void *)p;");
+  EXPECT_EQ(Tokens.size(), 11u) << Tokens;
+  EXPECT_TOKEN(Tokens[7], tok::r_paren, TT_CastRParen);
+
+  Tokens = annotate("delete/*comment*/[] (void *)p;");
+  EXPECT_EQ(Tokens.size(), 11u) << Tokens;
+  EXPECT_TOKEN(Tokens[7], tok::r_paren, TT_CastRParen);
+}
+
 } // 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] a7b5e5b - [clang-format] Fix formatting of macro definitions with a leading comment.

2022-02-09 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-02-09T22:39:59+01:00
New Revision: a7b5e5b413bd1654e8e96b9c7842c7c1ab0db58a

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

LOG: [clang-format] Fix formatting of macro definitions with a leading comment.

Fixes https://github.com/llvm/llvm-project/issues/43206.

Reviewed By: HazardyKnusperkeks

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 97a2cf367e80..0686aeb253ad 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -3551,6 +3551,8 @@ void UnwrappedLineParser::distributeComments(
 
 void UnwrappedLineParser::readToken(int LevelDifference) {
   SmallVector Comments;
+  bool PreviousWasComment = false;
+  bool FirstNonCommentOnLine = false;
   do {
 FormatTok = Tokens->getNextToken();
 assert(FormatTok);
@@ -3567,8 +3569,26 @@ void UnwrappedLineParser::readToken(int LevelDifference) 
{
   FormatTok->MustBreakBefore = true;
 }
 
+auto IsFirstNonCommentOnLine = [](bool FirstNonCommentOnLine,
+  const FormatToken &Tok,
+  bool PreviousWasComment) {
+  auto IsFirstOnLine = [](const FormatToken &Tok) {
+return Tok.HasUnescapedNewline || Tok.IsFirst;
+  };
+
+  // Consider preprocessor directives preceded by block comments as first
+  // on line.
+  if (PreviousWasComment)
+return FirstNonCommentOnLine || IsFirstOnLine(Tok);
+  return IsFirstOnLine(Tok);
+};
+
+FirstNonCommentOnLine = IsFirstNonCommentOnLine(
+FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
+PreviousWasComment = FormatTok->Tok.is(tok::comment);
+
 while (!Line->InPPDirective && FormatTok->Tok.is(tok::hash) &&
-   (FormatTok->HasUnescapedNewline || FormatTok->IsFirst)) {
+   FirstNonCommentOnLine) {
   distributeComments(Comments, FormatTok);
   Comments.clear();
   // If there is an unfinished unwrapped line, we flush the preprocessor
@@ -3587,6 +3607,9 @@ void UnwrappedLineParser::readToken(int LevelDifference) {
 Line->Level += PPBranchLevel;
   flushComments(isOnNewLine(*FormatTok));
   parsePPDirective();
+  PreviousWasComment = FormatTok->Tok.is(tok::comment);
+  FirstNonCommentOnLine = IsFirstNonCommentOnLine(
+  FirstNonCommentOnLine, *FormatTok, PreviousWasComment);
 }
 
 if (!PPStack.empty() && (PPStack.back().Kind == PP_Unreachable) &&

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 6f76a0c62edf..c7516427c2f4 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -1797,6 +1797,17 @@ TEST_F(FormatTest, FormatShortBracedStatements) {
 
 TEST_F(FormatTest, UnderstandsMacros) {
   verifyFormat("#define A (parentheses)");
+  verifyFormat("/* comment */ #define A (parentheses)");
+  verifyFormat("/* comment */ /* another comment */ #define A (parentheses)");
+  // Even the partial code should never be merged.
+  EXPECT_EQ("/* comment */ #define A (parentheses)\n"
+"#",
+format("/* comment */ #define A (parentheses)\n"
+   "#"));
+  verifyFormat("/* comment */ #define A (parentheses)\n"
+   "#\n");
+  verifyFormat("/* comment */ #define A (parentheses)\n"
+   "#define B (parentheses)");
   verifyFormat("#define true ((int)1)");
   verifyFormat("#define and(x)");
   verifyFormat("#define if(x) x");



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


[clang] 4efde1e - [clang-format] Move FormatToken::opensBlockOrBlockTypeList to source file. NFC.

2022-02-10 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-02-10T10:51:03+01:00
New Revision: 4efde1e554cce3f017b3d1ce700bd1860eed2ccd

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

LOG: [clang-format] Move FormatToken::opensBlockOrBlockTypeList to source file. 
NFC.

Added: 


Modified: 
clang/lib/Format/FormatToken.cpp
clang/lib/Format/FormatToken.h

Removed: 




diff  --git a/clang/lib/Format/FormatToken.cpp 
b/clang/lib/Format/FormatToken.cpp
index 40aa8f5cacb25..5577918d70927 100644
--- a/clang/lib/Format/FormatToken.cpp
+++ b/clang/lib/Format/FormatToken.cpp
@@ -74,6 +74,20 @@ bool FormatToken::isTypeOrIdentifier() const {
   return isSimpleTypeSpecifier() || Tok.isOneOf(tok::kw_auto, tok::identifier);
 }
 
+bool FormatToken::opensBlockOrBlockTypeList(const FormatStyle &Style) const {
+  // C# Does not indent object initialisers as continuations.
+  if (is(tok::l_brace) && getBlockKind() == BK_BracedInit && Style.isCSharp())
+return true;
+  if (is(TT_TemplateString) && opensScope())
+return true;
+  return is(TT_ArrayInitializerLSquare) || is(TT_ProtoExtensionLSquare) ||
+ (is(tok::l_brace) &&
+  (getBlockKind() == BK_Block || is(TT_DictLiteral) ||
+   (!Style.Cpp11BracedListStyle && NestingLevel == 0))) ||
+ (is(tok::less) && (Style.Language == FormatStyle::LK_Proto ||
+Style.Language == FormatStyle::LK_TextProto));
+}
+
 TokenRole::~TokenRole() {}
 
 void TokenRole::precomputeFormattingInfos(const FormatToken *Token) {}

diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index f116a89ac6440..6586ababd1e7b 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -696,19 +696,7 @@ struct FormatToken {
 
   /// Returns \c true if this tokens starts a block-type list, i.e. a
   /// list that should be indented with a block indent.
-  bool opensBlockOrBlockTypeList(const FormatStyle &Style) const {
-// C# Does not indent object initialisers as continuations.
-if (is(tok::l_brace) && getBlockKind() == BK_BracedInit && 
Style.isCSharp())
-  return true;
-if (is(TT_TemplateString) && opensScope())
-  return true;
-return is(TT_ArrayInitializerLSquare) || is(TT_ProtoExtensionLSquare) ||
-   (is(tok::l_brace) &&
-(getBlockKind() == BK_Block || is(TT_DictLiteral) ||
- (!Style.Cpp11BracedListStyle && NestingLevel == 0))) ||
-   (is(tok::less) && (Style.Language == FormatStyle::LK_Proto ||
-  Style.Language == FormatStyle::LK_TextProto));
-  }
+  LLVM_NODISCARD bool opensBlockOrBlockTypeList(const FormatStyle &Style) 
const;
 
   /// Returns whether the token is the left square bracket of a C++
   /// structured binding declaration.



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


[clang] 6c7e6fc - [clang-format] Do not remove required spaces when aligning tokens.

2022-02-10 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-02-10T19:15:27+01:00
New Revision: 6c7e6fc7b6654b7ecd364f352f8ffd6dfecbf77b

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

LOG: [clang-format] Do not remove required spaces when aligning tokens.

Fixes https://github.com/llvm/llvm-project/issues/44292.
Fixes https://github.com/llvm/llvm-project/issues/45874.

Reviewed By: HazardyKnusperkeks, owenpan

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/WhitespaceManager.cpp 
b/clang/lib/Format/WhitespaceManager.cpp
index 1d639275b1d59..758dc5860888e 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -331,6 +331,12 @@ AlignTokenSequence(const FormatStyle &Style, unsigned 
Start, unsigned End,
   FoundMatchOnLine = true;
   Shift = Column - Changes[i].StartOfTokenColumn;
   Changes[i].Spaces += Shift;
+  // FIXME: This is a workaround that should be removed when we fix
+  // http://llvm.org/PR53699. An assertion later below verifies this.
+  if (Changes[i].NewlinesBefore == 0)
+Changes[i].Spaces =
+std::max(Changes[i].Spaces,
+ static_cast(Changes[i].Tok->SpacesRequiredBefore));
 }
 
 // This is for function parameters that are split across multiple lines,
@@ -399,6 +405,12 @@ AlignTokenSequence(const FormatStyle &Style, unsigned 
Start, unsigned End,
 if (ContinuedStringLiteral)
   Changes[i].Spaces += Shift;
 
+// We should not remove required spaces unless we break the line before.
+assert(Changes[i].NewlinesBefore > 0 ||
+   Changes[i].Spaces >=
+   static_cast(Changes[i].Tok->SpacesRequiredBefore) ||
+   Changes[i].Tok->is(tok::eof));
+
 Changes[i].StartOfTokenColumn += Shift;
 if (i + 1 != Changes.size())
   Changes[i + 1].PreviousEndOfTokenColumn += Shift;

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index c7516427c2f45..8639a72eceb12 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -17277,6 +17277,31 @@ TEST_F(FormatTest, AlignConsecutiveDeclarations) {
"const unsigned   g;\n"
"Const unsigned   h;",
Alignment);
+
+  // See PR46529
+  FormatStyle BracedAlign = getLLVMStyle();
+  BracedAlign.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
+  verifyFormat("const auto result{[]() {\n"
+   "  const auto something = 1;\n"
+   "  return 2;\n"
+   "}};",
+   BracedAlign);
+  verifyFormat("int foo{[]() {\n"
+   "  int bar{0};\n"
+   "  return 0;\n"
+   "}()};",
+   BracedAlign);
+  BracedAlign.Cpp11BracedListStyle = false;
+  verifyFormat("const auto result{ []() {\n"
+   "  const auto something = 1;\n"
+   "  return 2;\n"
+   "} };",
+   BracedAlign);
+  verifyFormat("int foo{ []() {\n"
+   "  int bar{ 0 };\n"
+   "  return 0;\n"
+   "}() };",
+   BracedAlign);
 }
 
 TEST_F(FormatTest, AlignWithLineBreaks) {



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


[clang] a218706 - [clang-format] Add tests for spacing between ref-qualifier and `noexcept`. NFC.

2022-02-11 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-02-11T10:50:05+01:00
New Revision: a218706cba90248be0c60bd6a8f10dbcf0270955

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

LOG: [clang-format] Add tests for spacing between ref-qualifier and `noexcept`. 
NFC.

Cf. https://github.com/llvm/llvm-project/issues/44542.
Cf. 
https://github.com/llvm/llvm-project/commit/ae1b7859cbd61d2284d9690bc53482d0b6a46f63.

Added: 


Modified: 
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 8639a72eceb12..aa50d73499d04 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -9589,8 +9589,11 @@ TEST_F(FormatTest, UnderstandsOverloadedOperators) {
 }
 
 TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
+  verifyFormat("void A::b() && {}");
+  verifyFormat("void A::b() &&noexcept {}");
   verifyFormat("Deleted &operator=(const Deleted &) & = default;");
   verifyFormat("Deleted &operator=(const Deleted &) && = delete;");
+  verifyFormat("Deleted &operator=(const Deleted &) &noexcept = default;");
   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;");
   verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;");
   verifyFormat("Deleted &operator=(const Deleted &) &;");
@@ -9600,8 +9603,10 @@ TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
   verifyFormat("SomeType MemberFunction(const Deleted &) && {}");
   verifyFormat("SomeType MemberFunction(const Deleted &) && final {}");
   verifyFormat("SomeType MemberFunction(const Deleted &) && override {}");
+  verifyFormat("SomeType MemberFunction(const Deleted &) &&noexcept {}");
   verifyFormat("void Fn(T const &) const &;");
   verifyFormat("void Fn(T const volatile &&) const volatile &&;");
+  verifyFormat("void Fn(T const volatile &&) const volatile &&noexcept;");
   verifyFormat("template \n"
"void F(T) && = delete;",
getGoogleStyle());
@@ -9609,7 +9614,10 @@ TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
   FormatStyle AlignLeft = getLLVMStyle();
   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
   verifyFormat("void A::b() && {}", AlignLeft);
+  verifyFormat("void A::b() && noexcept {}", AlignLeft);
   verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft);
+  verifyFormat("Deleted& operator=(const Deleted&) & noexcept = default;",
+   AlignLeft);
   verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;",
AlignLeft);
   verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft);
@@ -9620,6 +9628,29 @@ TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
   verifyFormat("auto Function(T) & -> void;", AlignLeft);
   verifyFormat("void Fn(T const&) const&;", AlignLeft);
   verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft);
+  verifyFormat("void Fn(T const volatile&&) const volatile&& noexcept;",
+   AlignLeft);
+
+  FormatStyle AlignMiddle = getLLVMStyle();
+  AlignMiddle.PointerAlignment = FormatStyle::PAS_Middle;
+  verifyFormat("void A::b() && {}", AlignMiddle);
+  verifyFormat("void A::b() && noexcept {}", AlignMiddle);
+  verifyFormat("Deleted & operator=(const Deleted &) & = default;",
+   AlignMiddle);
+  verifyFormat("Deleted & operator=(const Deleted &) & noexcept = default;",
+   AlignMiddle);
+  verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;",
+   AlignMiddle);
+  verifyFormat("Deleted & operator=(const Deleted &) &;", AlignMiddle);
+  verifyFormat("SomeType MemberFunction(const Deleted &) &;", AlignMiddle);
+  verifyFormat("auto Function(T t) & -> void {}", AlignMiddle);
+  verifyFormat("auto Function(T... t) & -> void {}", AlignMiddle);
+  verifyFormat("auto Function(T) & -> void {}", AlignMiddle);
+  verifyFormat("auto Function(T) & -> void;", AlignMiddle);
+  verifyFormat("void Fn(T const &) const &;", AlignMiddle);
+  verifyFormat("void Fn(T const volatile &&) const volatile &&;", AlignMiddle);
+  verifyFormat("void Fn(T const volatile &&) const volatile && noexcept;",
+   AlignMiddle);
 
   FormatStyle Spaces = getLLVMStyle();
   Spaces.SpacesInCStyleCastParentheses = true;



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


[clang] 326cb51 - [clang-format] Simplify conditions in spaceRequiredBetween. NFC.

2022-02-11 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-02-11T12:01:24+01:00
New Revision: 326cb51b147a1de17ba0157c41c37243d3cbc0ff

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

LOG: [clang-format] Simplify conditions in spaceRequiredBetween. NFC.

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 28b244b9c59f1..ef4ce3483fcff 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3093,14 +3093,15 @@ bool TokenAnnotator::spaceRequiredBetween(const 
AnnotatedLine &Line,
 Right.Next->is(TT_RangeBasedForLoopColon))
   return getTokenPointerOrReferenceAlignment(Left) !=
  FormatStyle::PAS_Right;
-return !Right.isOneOf(TT_PointerOrReference, TT_ArraySubscriptLSquare,
-  tok::l_paren) &&
-   (getTokenPointerOrReferenceAlignment(Left) !=
-FormatStyle::PAS_Right &&
-!Line.IsMultiVariableDeclStmt) &&
-   Left.Previous &&
-   !Left.Previous->isOneOf(tok::l_paren, tok::coloncolon,
-   tok::l_square);
+if (Right.isOneOf(TT_PointerOrReference, TT_ArraySubscriptLSquare,
+  tok::l_paren))
+  return false;
+if (getTokenPointerOrReferenceAlignment(Left) == FormatStyle::PAS_Right)
+  return false;
+if (Line.IsMultiVariableDeclStmt)
+  return false;
+return Left.Previous && !Left.Previous->isOneOf(
+tok::l_paren, tok::coloncolon, tok::l_square);
   }
   // Ensure right pointer alignment with ellipsis e.g. int *...P
   if (Left.is(tok::ellipsis) && Left.Previous &&



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


[clang] fd16eee - [clang-format] Assert default style instead of commenting. NFC.

2022-02-11 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-02-11T12:01:25+01:00
New Revision: fd16eeea9d16150e35cadae1d77cee831b8cf510

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

LOG: [clang-format] Assert default style instead of commenting. NFC.

Added: 


Modified: 
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index aa50d73499d0..06b2fe5c650c 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -1975,9 +1975,8 @@ TEST_F(FormatTest, ElseIf) {
 
 TEST_F(FormatTest, SeparatePointerReferenceAlignment) {
   FormatStyle Style = getLLVMStyle();
-  // Check first the default LLVM style
-  // Style.PointerAlignment = FormatStyle::PAS_Right;
-  // Style.ReferenceAlignment = FormatStyle::RAS_Pointer;
+  EXPECT_EQ(Style.PointerAlignment, FormatStyle::PAS_Right);
+  EXPECT_EQ(Style.ReferenceAlignment, FormatStyle::RAS_Pointer);
   verifyFormat("int *f1(int *a, int &b, int &&c);", Style);
   verifyFormat("int &f2(int &&c, int *a, int &b);", Style);
   verifyFormat("int &&f3(int &b, int &&c, int *a);", Style);



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


[clang] 23f2785 - [clang-format] Avoid multiple calls to FormatToken::getNextNonComment(). NFC.

2022-02-11 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-02-11T15:20:11+01:00
New Revision: 23f27850b1e00e66ba19fc844ad8f2bd70268536

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

LOG: [clang-format] Avoid multiple calls to FormatToken::getNextNonComment(). 
NFC.

Added: 


Modified: 
clang/lib/Format/ContinuationIndenter.cpp
clang/lib/Format/TokenAnnotator.cpp
clang/lib/Format/UnwrappedLineFormatter.cpp

Removed: 




diff  --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index 871194f93f20..93d409118128 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -1221,10 +1221,17 @@ unsigned 
ContinuationIndenter::moveStateToNextToken(LineState &State,
   if (Current.is(TT_ArraySubscriptLSquare) &&
   State.Stack.back().StartOfArraySubscripts == 0)
 State.Stack.back().StartOfArraySubscripts = State.Column;
-  if (Current.is(TT_ConditionalExpr) && Current.is(tok::question) &&
-  ((Current.MustBreakBefore) ||
-   (Current.getNextNonComment() &&
-Current.getNextNonComment()->MustBreakBefore)))
+
+  auto IsWrappedConditional = [](const FormatToken &Tok) {
+if (!(Tok.is(TT_ConditionalExpr) && Tok.is(tok::question)))
+  return false;
+if (Tok.MustBreakBefore)
+  return true;
+
+const FormatToken *Next = Tok.getNextNonComment();
+return Next && Next->MustBreakBefore;
+  };
+  if (IsWrappedConditional(Current))
 State.Stack.back().IsWrappedConditional = true;
   if (Style.BreakBeforeTernaryOperators && Current.is(tok::question))
 State.Stack.back().QuestionColumn = State.Column;

diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index ef4ce3483fcf..70f92c26fa8d 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3598,7 +3598,8 @@ bool TokenAnnotator::spaceRequiredBefore(const 
AnnotatedLine &Line,
   if (Right.is(tok::colon)) {
 if (Line.First->isOneOf(tok::kw_default, tok::kw_case))
   return Style.SpaceBeforeCaseColon;
-if (!Right.getNextNonComment() || Right.getNextNonComment()->is(tok::semi))
+const FormatToken *Next = Right.getNextNonComment();
+if (!Next || Next->is(tok::semi))
   return false;
 if (Right.is(TT_ObjCMethodExpr))
   return false;

diff  --git a/clang/lib/Format/UnwrappedLineFormatter.cpp 
b/clang/lib/Format/UnwrappedLineFormatter.cpp
index 9f49410f741a..88efda487eeb 100644
--- a/clang/lib/Format/UnwrappedLineFormatter.cpp
+++ b/clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -700,9 +700,13 @@ class LineJoiner {
 
 if (Line.Last->is(tok::l_brace)) {
   FormatToken *Tok = I[1]->First;
-  if (Tok->is(tok::r_brace) && !Tok->MustBreakBefore &&
-  (Tok->getNextNonComment() == nullptr ||
-   Tok->getNextNonComment()->is(tok::semi))) {
+  auto ShouldMerge = [Tok]() {
+if (Tok->isNot(tok::r_brace) || Tok->MustBreakBefore)
+  return false;
+const FormatToken *Next = Tok->getNextNonComment();
+return !Next || Next->is(tok::semi);
+  };
+  if (ShouldMerge()) {
 // We merge empty blocks even if the line exceeds the column limit.
 Tok->SpacesRequiredBefore = Style.SpaceInEmptyBlock ? 1 : 0;
 Tok->CanBreakBefore = true;



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


[clang] 0104f5e - [clang-format] Mark FormatToken::getNextNonComment() nodiscard. NFC.

2022-02-11 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-02-11T15:20:11+01:00
New Revision: 0104f5efede22890c356810f992162a84cd615dd

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

LOG: [clang-format] Mark FormatToken::getNextNonComment() nodiscard. NFC.

Added: 


Modified: 
clang/lib/Format/FormatToken.h

Removed: 




diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index 6586ababd1e7b..4c03f436dde3e 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -687,7 +687,7 @@ struct FormatToken {
   }
 
   /// Returns the next token ignoring comments.
-  const FormatToken *getNextNonComment() const {
+  LLVM_NODISCARD const FormatToken *getNextNonComment() const {
 const FormatToken *Tok = Next;
 while (Tok && Tok->is(tok::comment))
   Tok = Tok->Next;



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


[clang] 7d5062c - [clang-format] Remove unnecessary parentheses in return statements. NFC.

2022-02-12 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-02-12T21:25:52+01:00
New Revision: 7d5062c6ac868537605dd0860b2714aba9ece90d

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

LOG: [clang-format] Remove unnecessary parentheses in return statements. NFC.

Added: 


Modified: 
clang/lib/Format/ContinuationIndenter.cpp
clang/lib/Format/FormatTokenLexer.cpp
clang/lib/Format/NamespaceEndCommentsFixer.cpp
clang/lib/Format/TokenAnnotator.cpp

Removed: 




diff  --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index 42c3d2e4326b9..23892be8e9e8e 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -331,7 +331,7 @@ bool ContinuationIndenter::mustBreak(const LineState 
&State) {
   if (Style.BraceWrapping.BeforeLambdaBody && Current.CanBreakBefore &&
   Current.is(TT_LambdaLBrace) && Previous.isNot(TT_LineComment)) {
 auto LambdaBodyLength = getLengthToMatchingParen(Current, State.Stack);
-return (LambdaBodyLength > getColumnLimit(State));
+return LambdaBodyLength > getColumnLimit(State);
   }
   if (Current.MustBreakBefore || Current.is(TT_InlineASMColon))
 return true;
@@ -1234,7 +1234,7 @@ static bool hasNestedBlockInlined(const FormatToken 
*Previous,
 return true;
 
   // Also a nested block if contains a lambda inside function with 1 parameter
-  return (Style.BraceWrapping.BeforeLambdaBody && 
Current.is(TT_LambdaLSquare));
+  return Style.BraceWrapping.BeforeLambdaBody && Current.is(TT_LambdaLSquare);
 }
 
 unsigned ContinuationIndenter::moveStateToNextToken(LineState &State,

diff  --git a/clang/lib/Format/FormatTokenLexer.cpp 
b/clang/lib/Format/FormatTokenLexer.cpp
index 0ecae6af4c46b..1540c14686faa 100644
--- a/clang/lib/Format/FormatTokenLexer.cpp
+++ b/clang/lib/Format/FormatTokenLexer.cpp
@@ -500,7 +500,7 @@ bool FormatTokenLexer::canPrecedeRegexLiteral(FormatToken 
*Prev) {
   // `!` is an unary prefix operator, but also a post-fix operator that casts
   // away nullability, so the same check applies.
   if (Prev->isOneOf(tok::plusplus, tok::minusminus, tok::exclaim))
-return (Tokens.size() < 3 || precedesOperand(Tokens[Tokens.size() - 3]));
+return Tokens.size() < 3 || precedesOperand(Tokens[Tokens.size() - 3]);
 
   // The previous token must introduce an operand location where regex
   // literals can occur.

diff  --git a/clang/lib/Format/NamespaceEndCommentsFixer.cpp 
b/clang/lib/Format/NamespaceEndCommentsFixer.cpp
index 00d161890906f..65f965548da37 100644
--- a/clang/lib/Format/NamespaceEndCommentsFixer.cpp
+++ b/clang/lib/Format/NamespaceEndCommentsFixer.cpp
@@ -136,7 +136,7 @@ bool validEndComment(const FormatToken *RBraceTok, 
StringRef NamespaceName,
 return false;
   NamespaceNameInComment = Groups.size() > 2 ? Groups[2] : "";
 
-  return (NamespaceNameInComment == NamespaceName);
+  return NamespaceNameInComment == NamespaceName;
 }
 
 void addEndComment(const FormatToken *RBraceTok, StringRef EndCommentText,

diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index dabecbf9c74ab..f1db5224fc55b 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1615,10 +1615,10 @@ class AnnotatingParser {
   PriorLeadingIdentifier->is(tok::kw_explicit))
 PriorLeadingIdentifier = PriorLeadingIdentifier->Previous;
 
-  return (PriorLeadingIdentifier &&
-  (PriorLeadingIdentifier->is(TT_TemplateCloser) ||
-   PriorLeadingIdentifier->ClosesRequiresClause) &&
-  LeadingIdentifier->TokenText == Current.Next->TokenText);
+  return PriorLeadingIdentifier &&
+ (PriorLeadingIdentifier->is(TT_TemplateCloser) ||
+  PriorLeadingIdentifier->ClosesRequiresClause) &&
+ LeadingIdentifier->TokenText == Current.Next->TokenText;
 }
   }
 }
@@ -1868,7 +1868,7 @@ class AnnotatingParser {
   return true;
 
 // const a = in JavaScript.
-return (Style.isJavaScript() && PreviousNotConst->is(tok::kw_const));
+return Style.isJavaScript() && PreviousNotConst->is(tok::kw_const);
   }
 
   /// Determine whether ')' is ending a cast.
@@ -3085,12 +3085,12 @@ bool TokenAnnotator::spaceRequiredBetween(const 
AnnotatedLine &Line,
 Right.Next->Next->is(TT_RangeBasedForLoopColon))
   return getTokenPointerOrReferenceAlignment(Right) !=
  FormatStyle::PAS_Left;
-return (
-(!Left.isOneOf(TT_PointerOrReference, tok::l_paren) &&
- (getTokenPointerOrReferenceAlignment(Right) != FormatStyle::PAS_Left 
||
-  (Line.IsMultiVariableDeclStmt &&
-   (Left.NestingLevel == 0 ||
-(Left

[clang] 9cb9445 - [clang-format] Correctly format loops and `if` statements even if preceded with comments.

2022-02-13 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-02-13T21:22:17+01:00
New Revision: 9cb944597907458ce9c2f6bd0ecc9723b674b77f

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

LOG: [clang-format] Correctly format loops and `if` statements even if preceded 
with comments.

Fixes https://github.com/llvm/llvm-project/issues/53758.

Braces in loops and in `if` statements with leading (block) comments were 
formatted according to `BraceWrapping.AfterFunction` and not 
`AllowShortBlocksOnASingleLine`/`AllowShortLoopsOnASingleLine`/`AllowShortIfStatementsOnASingleLine`.

Previously, the code:
```
while (true) {
  f();
}
/*comment*/ while (true) {
  f();
}
```

was incorrectly formatted to:
```
while (true) {
  f();
}
/*comment*/ while (true) { f(); }
```

when using config:
```
BasedOnStyle: LLVM
BreakBeforeBraces: Custom
BraceWrapping:
  AfterFunction: false
AllowShortBlocksOnASingleLine: false
AllowShortLoopsOnASingleLine: false
```

and it was (correctly but by chance) formatted to:
```
while (true) {
  f();
}
/*comment*/ while (true) {
  f();
}
```

when using enabling brace wrapping after functions:
```
BasedOnStyle: LLVM
BreakBeforeBraces: Custom
BraceWrapping:
  AfterFunction: true
AllowShortBlocksOnASingleLine: false
AllowShortLoopsOnASingleLine: false
```

Reviewed By: MyDeveloperDay, HazardyKnusperkeks, owenpan

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineFormatter.cpp 
b/clang/lib/Format/UnwrappedLineFormatter.cpp
index 88efda487eeb6..883030cb3dc16 100644
--- a/clang/lib/Format/UnwrappedLineFormatter.cpp
+++ b/clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -319,6 +319,15 @@ class LineJoiner {
 
 bool MergeShortFunctions = ShouldMergeShortFunctions();
 
+const FormatToken *FirstNonComment = TheLine->First;
+if (FirstNonComment->is(tok::comment)) {
+  FirstNonComment = FirstNonComment->getNextNonComment();
+  if (!FirstNonComment)
+return 0;
+}
+// FIXME: There are probably cases where we should use FirstNonComment
+// instead of TheLine->First.
+
 if (Style.CompactNamespaces) {
   if (auto nsToken = TheLine->First->getNamespaceToken()) {
 int i = 0;
@@ -358,9 +367,9 @@ class LineJoiner {
 if (TheLine->Last->is(TT_FunctionLBrace) && TheLine->First != 
TheLine->Last)
   return MergeShortFunctions ? tryMergeSimpleBlock(I, E, Limit) : 0;
 // Try to merge a control statement block with left brace unwrapped.
-if (TheLine->Last->is(tok::l_brace) && TheLine->First != TheLine->Last &&
-TheLine->First->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for,
-TT_ForEachMacro)) {
+if (TheLine->Last->is(tok::l_brace) && FirstNonComment != TheLine->Last &&
+FirstNonComment->isOneOf(tok::kw_if, tok::kw_while, tok::kw_for,
+ TT_ForEachMacro)) {
   return Style.AllowShortBlocksOnASingleLine != FormatStyle::SBS_Never
  ? tryMergeSimpleBlock(I, E, Limit)
  : 0;

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 0d315734bc951..40de29e58737f 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -1520,6 +1520,36 @@ TEST_F(FormatTest, FormatLoopsWithoutCompoundStatement) {
 
 TEST_F(FormatTest, FormatShortBracedStatements) {
   FormatStyle AllowSimpleBracedStatements = getLLVMStyle();
+  EXPECT_EQ(AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine, false);
+  EXPECT_EQ(AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine,
+FormatStyle::SIS_Never);
+  EXPECT_EQ(AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine, false);
+  EXPECT_EQ(AllowSimpleBracedStatements.BraceWrapping.AfterFunction, false);
+  verifyFormat("for (;;) {\n"
+   "  f();\n"
+   "}");
+  verifyFormat("/*comment*/ for (;;) {\n"
+   "  f();\n"
+   "}");
+  verifyFormat("BOOST_FOREACH (int v, vec) {\n"
+   "  f();\n"
+   "}");
+  verifyFormat("/*comment*/ BOOST_FOREACH (int v, vec) {\n"
+   "  f();\n"
+   "}");
+  verifyFormat("while (true) {\n"
+   "  f();\n"
+   "}");
+  verifyFormat("/*comment*/ while (true) {\n"
+   "  f();\n"
+   "}");
+  verifyFormat("if (true) {\n"
+   "  f();\n"
+   "}");
+  verifyFormat("/*comment*/ if (true) {\n"
+   "  f();\n"
+   "}");
+
   AllowSimpleBracedStatements.IfMacros.push_back("MYIF");
   // Where line-lengths matter, a 2-letter synonym that m

[clang] 25282bd - [clang-format] Handle PointerAlignment in `if` and `switch` statements with initializers (C++17) the same way as in `for` loops.

2022-02-13 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-02-13T21:36:58+01:00
New Revision: 25282bd6c4bf54a21c0f8dbf00db6e70922c02fa

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

LOG: [clang-format] Handle PointerAlignment in `if` and `switch` statements 
with initializers (C++17) the same way as in `for` loops.

Reviewed By: MyDeveloperDay, owenpan

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index f1db5224fc55b..a6c6ddcad117b 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -26,6 +26,13 @@ namespace format {
 
 namespace {
 
+/// Returns \c true if the line starts with a token that can start a statement
+/// with an initializer.
+static bool startsWithInitStatement(const AnnotatedLine &Line) {
+  return Line.startsWith(tok::kw_for) || Line.startsWith(tok::kw_if) ||
+ Line.startsWith(tok::kw_switch);
+}
+
 /// Returns \c true if the token can be used as an identifier in
 /// an Objective-C \c \@selector, \c false otherwise.
 ///
@@ -1135,7 +1142,7 @@ class AnnotatingParser {
   else if (Contexts.back().InInheritanceList)
 Tok->setType(TT_InheritanceComma);
   else if (Contexts.back().FirstStartOfName &&
-   (Contexts.size() == 1 || Line.startsWith(tok::kw_for))) {
+   (Contexts.size() == 1 || startsWithInitStatement(Line))) {
 Contexts.back().FirstStartOfName->PartOfMultiVariableDeclStmt = true;
 Line.IsMultiVariableDeclStmt = true;
   }
@@ -3090,7 +3097,7 @@ bool TokenAnnotator::spaceRequiredBetween(const 
AnnotatedLine &Line,
 FormatStyle::PAS_Left ||
 (Line.IsMultiVariableDeclStmt &&
  (Left.NestingLevel == 0 ||
-  (Left.NestingLevel == 1 && Line.First->is(tok::kw_for);
+  (Left.NestingLevel == 1 && startsWithInitStatement(Line);
   }
   if (Right.is(TT_FunctionTypeLParen) && Left.isNot(tok::l_paren) &&
   (!Left.is(TT_PointerOrReference) ||

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 40de29e58737f..fc2b121faee02 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -8396,6 +8396,12 @@ TEST_F(FormatTest, DeclarationsOfMultipleVariables) {
Style);
   verifyFormat("vector a, b;", Style);
   verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style);
+  verifyFormat("/*comment*/ for (int *p, *q; p != q; p = p->next) {\n}", 
Style);
+  verifyFormat("if (int *p, *q; p != q) {\n  p = p->next;\n}", Style);
+  verifyFormat("/*comment*/ if (int *p, *q; p != q) {\n  p = p->next;\n}",
+   Style);
+  verifyFormat("switch (int *p, *q; p != q) {\n  default:\nbreak;\n}", 
Style);
+  verifyFormat("/*comment*/ switch (int *p, *q; p != q) {\n  default:\n
break;\n}", Style);
 }
 
 TEST_F(FormatTest, ConditionalExpressionsInBrackets) {



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


[clang] 09559bc - Avoid a vulgarism. NFC.

2022-02-13 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-02-13T22:01:06+01:00
New Revision: 09559bc59a718e597725c7d9747350e9c649fd0e

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

LOG: Avoid a vulgarism. NFC.

Added: 


Modified: 
clang/unittests/Format/FormatTestComments.cpp

Removed: 




diff  --git a/clang/unittests/Format/FormatTestComments.cpp 
b/clang/unittests/Format/FormatTestComments.cpp
index 282bc46cd048..dcfd219484fa 100644
--- a/clang/unittests/Format/FormatTestComments.cpp
+++ b/clang/unittests/Format/FormatTestComments.cpp
@@ -3660,17 +3660,17 @@ TEST_F(FormatTestComments, SpaceAtLineCommentBegin) {
 format(WrapCode, Style));
 
   Style = getLLVMStyleWithColumns(20);
-  StringRef AShitloadOfSpaces = "//  This are more spaces "
-"than the ColumnLimit, what now?\n"
-"\n"
-"//   Comment\n"
-"\n"
-"// This is a text to split in multiple "
-"lines, please. Thank you very much!\n"
-"\n"
-"// A comment with\n"
-"//   some indentation that has to be split.\n"
-"// And now without";
+  StringRef LotsOfSpaces = "//  This are more spaces "
+   "than the ColumnLimit, what now?\n"
+   "\n"
+   "//   Comment\n"
+   "\n"
+   "// This is a text to split in multiple "
+   "lines, please. Thank you very much!\n"
+   "\n"
+   "// A comment with\n"
+   "//   some indentation that has to be split.\n"
+   "// And now without";
   EXPECT_EQ("//  This are more spaces "
 "than the ColumnLimit, what now?\n"
 "\n"
@@ -3688,7 +3688,7 @@ TEST_F(FormatTestComments, SpaceAtLineCommentBegin) {
 "//   that has to be\n"
 "//   split.\n"
 "// And now without",
-format(AShitloadOfSpaces, Style));
+format(LotsOfSpaces, Style));
 
   Style.SpacesInLineCommentPrefix = {0, 0};
   EXPECT_EQ("//This are more\n"
@@ -3709,7 +3709,7 @@ TEST_F(FormatTestComments, SpaceAtLineCommentBegin) {
 "//  that has to be\n"
 "//  split.\n"
 "//And now without",
-format(AShitloadOfSpaces, Style));
+format(LotsOfSpaces, Style));
 
   Style.SpacesInLineCommentPrefix = {3, 3};
   EXPECT_EQ("//   This are more\n"
@@ -3731,7 +3731,7 @@ TEST_F(FormatTestComments, SpaceAtLineCommentBegin) {
 "// that has to\n"
 "// be split.\n"
 "//   And now without",
-format(AShitloadOfSpaces, Style));
+format(LotsOfSpaces, Style));
 
   Style.SpacesInLineCommentPrefix = {30, -1u};
   EXPECT_EQ("//  This are more spaces than the "
@@ -3746,7 +3746,7 @@ TEST_F(FormatTestComments, SpaceAtLineCommentBegin) {
 "//some indentation that has to be 
"
 "split.\n"
 "//  And now without",
-format(AShitloadOfSpaces, Style));
+format(LotsOfSpaces, Style));
 
   Style.SpacesInLineCommentPrefix = {2, 4};
   EXPECT_EQ("//  A Comment to be\n"



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


[clang] e01f624 - [clang-format] Fix PointerAlignment within lambdas in a multi-variable declaration statement.

2022-02-14 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-02-14T09:41:24+01:00
New Revision: e01f624adb0ed5d0f1369b0679a64484bac10d02

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

LOG: [clang-format] Fix PointerAlignment within lambdas in a multi-variable 
declaration statement.

Fixes https://github.com/llvm/llvm-project/issues/43115.

Also, handle while loops with initializers (C++20) the same way as for loops.

Reviewed By: HazardyKnusperkeks, owenpan

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index a6c6ddcad117b..72f49478d5b4b 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3134,7 +3134,15 @@ bool TokenAnnotator::spaceRequiredBetween(const 
AnnotatedLine &Line,
   return false;
 if (getTokenPointerOrReferenceAlignment(Left) == FormatStyle::PAS_Right)
   return false;
-if (Line.IsMultiVariableDeclStmt)
+// FIXME: Setting IsMultiVariableDeclStmt for the whole line is 
error-prone,
+// because it does not take into account nested scopes like lambdas.
+// In multi-variable declaration statements, attach */& to the variable
+// independently of the style. However, avoid doing it if we are in a 
nested
+// scope, e.g. lambda. We still need to special-case statements with
+// initializers.
+if (Line.IsMultiVariableDeclStmt &&
+(Left.NestingLevel == Line.First->NestingLevel ||
+ startsWithInitStatement(Line)))
   return false;
 return Left.Previous && !Left.Previous->isOneOf(
 tok::l_paren, tok::coloncolon, tok::l_square);

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index fc2b121faee02..689600c591b26 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -2031,6 +2031,10 @@ TEST_F(FormatTest, SeparatePointerReferenceAlignment) {
   verifyFormat("for (int x = 0; int &c : {1, 2, 3})", Style);
   verifyFormat("for (f(); auto &c : {1, 2, 3})", Style);
   verifyFormat("for (f(); int &c : {1, 2, 3})", Style);
+  verifyFormat(
+  "function res1 = [](int &a) { return 0; },\n"
+  " res2 = [](int &a) { return 0; };",
+  Style);
 
   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
   verifyFormat("Const unsigned int *c;\n"
@@ -2068,6 +2072,10 @@ TEST_F(FormatTest, SeparatePointerReferenceAlignment) {
   verifyFormat("for (int x = 0; int& c : {1, 2, 3})", Style);
   verifyFormat("for (f(); auto& c : {1, 2, 3})", Style);
   verifyFormat("for (f(); int& c : {1, 2, 3})", Style);
+  verifyFormat(
+  "function res1 = [](int& a) { return 0; },\n"
+  "res2 = [](int& a) { return 0; };",
+  Style);
 
   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
   verifyFormat("Const unsigned int* c;\n"
@@ -2121,6 +2129,10 @@ TEST_F(FormatTest, SeparatePointerReferenceAlignment) {
   verifyFormat("for (int x = 0; int & c : {1, 2, 3})", Style);
   verifyFormat("for (f(); auto & c : {1, 2, 3})", Style);
   verifyFormat("for (f(); int & c : {1, 2, 3})", Style);
+  verifyFormat(
+  "function res1 = [](int & a) { return 0; },\n"
+  " res2 = [](int & a) { return 0; };",
+  Style);
 
   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
   verifyFormat("Const unsigned int*  c;\n"



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


[clang] e967d97 - [clang-format] Fix SpacesInLineCommentPrefix deleting tokens.

2022-02-14 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-02-14T09:53:16+01:00
New Revision: e967d97a35a93c883528a9672159edff05f5addb

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

LOG: [clang-format] Fix SpacesInLineCommentPrefix deleting tokens.

Fixes https://github.com/llvm/llvm-project/issues/53799.

Reviewed By: HazardyKnusperkeks, owenpan

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/BreakableToken.cpp 
b/clang/lib/Format/BreakableToken.cpp
index ef8dc2a864a2a..5138c7cd42cc6 100644
--- a/clang/lib/Format/BreakableToken.cpp
+++ b/clang/lib/Format/BreakableToken.cpp
@@ -747,6 +747,7 @@ BreakableLineCommentSection::BreakableLineCommentSection(
   assert(Tok.is(TT_LineComment) &&
  "line comment section must start with a line comment");
   FormatToken *LineTok = nullptr;
+  const int Minimum = Style.SpacesInLineCommentPrefix.Minimum;
   // How many spaces we changed in the first line of the section, this will be
   // applied in all following lines
   int FirstLineSpaceChange = 0;
@@ -769,7 +770,7 @@ BreakableLineCommentSection::BreakableLineCommentSection(
   Lines[i] = Lines[i].ltrim(Blanks);
   StringRef IndentPrefix = getLineCommentIndentPrefix(Lines[i], Style);
   OriginalPrefix[i] = IndentPrefix;
-  const unsigned SpacesInPrefix = llvm::count(IndentPrefix, ' ');
+  const int SpacesInPrefix = llvm::count(IndentPrefix, ' ');
 
   // This lambda also considers multibyte character that is not handled in
   // functions like isPunctuation provided by CharInfo.
@@ -792,12 +793,11 @@ BreakableLineCommentSection::BreakableLineCommentSection(
   // e.g. from "///" to "//".
   if (i == 0 || OriginalPrefix[i].rtrim(Blanks) !=
 OriginalPrefix[i - 1].rtrim(Blanks)) {
-if (SpacesInPrefix < Style.SpacesInLineCommentPrefix.Minimum &&
-Lines[i].size() > IndentPrefix.size() &&
+if (SpacesInPrefix < Minimum && Lines[i].size() > IndentPrefix.size() 
&&
 !NoSpaceBeforeFirstCommentChar()) {
-  FirstLineSpaceChange =
-  Style.SpacesInLineCommentPrefix.Minimum - SpacesInPrefix;
-} else if (SpacesInPrefix > Style.SpacesInLineCommentPrefix.Maximum) {
+  FirstLineSpaceChange = Minimum - SpacesInPrefix;
+} else if (static_cast(SpacesInPrefix) >
+   Style.SpacesInLineCommentPrefix.Maximum) {
   FirstLineSpaceChange =
   Style.SpacesInLineCommentPrefix.Maximum - SpacesInPrefix;
 } else {
@@ -808,10 +808,9 @@ BreakableLineCommentSection::BreakableLineCommentSection(
   if (Lines[i].size() != IndentPrefix.size()) {
 PrefixSpaceChange[i] = FirstLineSpaceChange;
 
-if (SpacesInPrefix + PrefixSpaceChange[i] <
-Style.SpacesInLineCommentPrefix.Minimum) {
-  PrefixSpaceChange[i] += Style.SpacesInLineCommentPrefix.Minimum -
-  (SpacesInPrefix + PrefixSpaceChange[i]);
+if (SpacesInPrefix + PrefixSpaceChange[i] < Minimum) {
+  PrefixSpaceChange[i] +=
+  Minimum - (SpacesInPrefix + PrefixSpaceChange[i]);
 }
 
 assert(Lines[i].size() > IndentPrefix.size());

diff  --git a/clang/unittests/Format/FormatTestComments.cpp 
b/clang/unittests/Format/FormatTestComments.cpp
index dcfd219484fa5..8cdca0eb5900a 100644
--- a/clang/unittests/Format/FormatTestComments.cpp
+++ b/clang/unittests/Format/FormatTestComments.cpp
@@ -3645,6 +3645,11 @@ TEST_F(FormatTestComments, SpaceAtLineCommentBegin) {
 "   // World\n"
 "}",
 format(WrapCode, Style));
+  EXPECT_EQ("// x\n"
+"// y",
+format("//   x\n"
+   "// y",
+   Style));
 
   Style.SpacesInLineCommentPrefix = {3, 3};
   EXPECT_EQ("//   Lorem ipsum\n"



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


[clang] c72fdad - [clang-format] Reformat. NFC.

2022-02-14 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-02-14T14:05:05+01:00
New Revision: c72fdad71b6a9e5ca39fdcc7cb8bd476ecc5bbd7

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

LOG: [clang-format] Reformat. NFC.

Added: 


Modified: 
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 689600c591b26..d230964cd2860 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -8412,8 +8412,11 @@ TEST_F(FormatTest, DeclarationsOfMultipleVariables) {
   verifyFormat("if (int *p, *q; p != q) {\n  p = p->next;\n}", Style);
   verifyFormat("/*comment*/ if (int *p, *q; p != q) {\n  p = p->next;\n}",
Style);
-  verifyFormat("switch (int *p, *q; p != q) {\n  default:\nbreak;\n}", 
Style);
-  verifyFormat("/*comment*/ switch (int *p, *q; p != q) {\n  default:\n
break;\n}", Style);
+  verifyFormat("switch (int *p, *q; p != q) {\n  default:\nbreak;\n}",
+   Style);
+  verifyFormat(
+  "/*comment*/ switch (int *p, *q; p != q) {\n  default:\nbreak;\n}",
+  Style);
 }
 
 TEST_F(FormatTest, ConditionalExpressionsInBrackets) {



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


[clang] e21db15 - [clang-format] Honour PointerAlignment in statements with initializers.

2022-02-15 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-02-15T18:06:32+01:00
New Revision: e21db15be8126004304b813e5ff87c7ecbed06bf

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

LOG: [clang-format] Honour PointerAlignment in statements with initializers.

Fixes https://github.com/llvm/llvm-project/issues/53843.

Reviewed By: HazardyKnusperkeks, owenpan

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 72f49478d5b4b..a2985eb75a195 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3142,7 +3142,8 @@ bool TokenAnnotator::spaceRequiredBetween(const 
AnnotatedLine &Line,
 // initializers.
 if (Line.IsMultiVariableDeclStmt &&
 (Left.NestingLevel == Line.First->NestingLevel ||
- startsWithInitStatement(Line)))
+ ((Left.NestingLevel == Line.First->NestingLevel + 1) &&
+  startsWithInitStatement(Line
   return false;
 return Left.Previous && !Left.Previous->isOneOf(
 tok::l_paren, tok::coloncolon, tok::l_square);

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index d230964cd2860..1b99b53bbee55 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -8417,6 +8417,13 @@ TEST_F(FormatTest, DeclarationsOfMultipleVariables) {
   verifyFormat(
   "/*comment*/ switch (int *p, *q; p != q) {\n  default:\nbreak;\n}",
   Style);
+
+  verifyFormat("if ([](int* p, int* q) {}()) {\n}", Style);
+  verifyFormat("for ([](int* p, int* q) {}();;) {\n}", Style);
+  verifyFormat("for (; [](int* p, int* q) {}();) {\n}", Style);
+  verifyFormat("for (;; [](int* p, int* q) {}()) {\n}", Style);
+  verifyFormat("switch ([](int* p, int* q) {}()) {\n  default:\nbreak;\n}",
+   Style);
 }
 
 TEST_F(FormatTest, ConditionalExpressionsInBrackets) {



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


[clang] fdee512 - [clang-format] Add test for SpacesInLineCommentPrefix. NFC.

2022-02-16 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-02-16T13:54:55+01:00
New Revision: fdee51204848dce5e0c39db332a7c488dc5b333f

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

LOG: [clang-format] Add test for SpacesInLineCommentPrefix. NFC.

Fixes https://github.com/llvm/llvm-project/issues/52649.
This was already fixed in commit 
https://github.com/llvm/llvm-project/commit/e967d97a35a93c883528a9672159edff05f5addb.

Added: 


Modified: 
clang/unittests/Format/FormatTestComments.cpp

Removed: 




diff  --git a/clang/unittests/Format/FormatTestComments.cpp 
b/clang/unittests/Format/FormatTestComments.cpp
index 8cdca0eb5900a..c988a2869e568 100644
--- a/clang/unittests/Format/FormatTestComments.cpp
+++ b/clang/unittests/Format/FormatTestComments.cpp
@@ -3650,6 +3650,13 @@ TEST_F(FormatTestComments, SpaceAtLineCommentBegin) {
 format("//   x\n"
"// y",
Style));
+  EXPECT_EQ(
+  "// loong\n"
+  "// commentcomments\n"
+  "// normal comments",
+  format("//loong 
commentcomments\n"
+ "// normal comments",
+ Style));
 
   Style.SpacesInLineCommentPrefix = {3, 3};
   EXPECT_EQ("//   Lorem ipsum\n"



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


[clang] 05a77fc - [clang-format] Fall through and avoid an unnecessary check. NFC.

2022-02-16 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-02-16T22:07:09+01:00
New Revision: 05a77fc3f97adddc1af3d4fb6d4234047ed09a99

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

LOG: [clang-format] Fall through and avoid an unnecessary check. NFC.

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index cb5baae565321..f3885a1f683bc 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -982,10 +982,11 @@ class AnnotatingParser {
 Tok->setType(TT_JsTypeOperator);
   break;
 case tok::kw_if:
-case tok::kw_while:
-  if (Tok->is(tok::kw_if) && CurrentToken &&
+  if (CurrentToken &&
   CurrentToken->isOneOf(tok::kw_constexpr, tok::identifier))
 next();
+  LLVM_FALLTHROUGH;
+case tok::kw_while:
   if (CurrentToken && CurrentToken->is(tok::l_paren)) {
 next();
 if (!parseParens(/*LookForDecls=*/true))



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


[clang] d81f003 - [clang-format] Fix formatting of struct-like records followed by variable declaration.

2022-02-16 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-02-16T22:37:32+01:00
New Revision: d81f003ce1419aee6cfb8d26f0bca9153278872a

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

LOG: [clang-format] Fix formatting of struct-like records followed by variable 
declaration.

Fixes https://github.com/llvm/llvm-project/issues/24781.
Fixes https://github.com/llvm/llvm-project/issues/38160.

This patch splits `TT_RecordLBrace` for classes/enums/structs/unions (and other 
records, e.g. interfaces) and uses the brace type to avoid the error-prone 
scanning for record token.

The mentioned bugs were provoked by the scanning being too limited (and so not 
considering `const` or `constexpr`, or other qualifiers, on an anonymous struct 
variable declaration).

Moreover, the proposed solution is more efficient as we parse tokens once only 
(scanning being parsing too).

Reviewed By: MyDeveloperDay, HazardyKnusperkeks

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index fee365ecc8f91..6aaf66c7bb7e5 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -37,6 +37,7 @@ namespace format {
   TYPE(BlockComment)   
\
   TYPE(BracedListLBrace)   
\
   TYPE(CastRParen) 
\
+  TYPE(ClassLBrace)
\
   TYPE(CompoundRequirementLBrace)  
\
   TYPE(ConditionalExpr)
\
   TYPE(ConflictAlternative)
\
@@ -47,6 +48,7 @@ namespace format {
   TYPE(DesignatedInitializerLSquare)   
\
   TYPE(DesignatedInitializerPeriod)
\
   TYPE(DictLiteral)
\
+  TYPE(EnumLBrace) 
\
   TYPE(FatArrow)   
\
   TYPE(ForEachMacro)   
\
   TYPE(FunctionAnnotationRParen)   
\
@@ -108,6 +110,7 @@ namespace format {
   TYPE(StartOfName)
\
   TYPE(StatementAttributeLikeMacro)
\
   TYPE(StatementMacro) 
\
+  TYPE(StructLBrace)   
\
   TYPE(StructuredBindingLSquare)   
\
   TYPE(TemplateCloser) 
\
   TYPE(TemplateOpener) 
\
@@ -119,6 +122,7 @@ namespace format {
   TYPE(TypeDeclarationParen)   
\
   TYPE(TypenameMacro)  
\
   TYPE(UnaryOperator)  
\
+  TYPE(UnionLBrace)
\
   TYPE(UntouchableMacroFunc)   
\
   TYPE(CSharpStringLiteral)
\
   TYPE(CSharpNamedArgumentColon)   
\

diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index f3885a1f683bc..206fa4541217c 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1425,11 +1425,12 @@ class AnnotatingParser {
 TT_LambdaArrow, TT_NamespaceMacro, TT_OverloadedOperator,
 TT_RegexLiteral, TT_TemplateString, TT_ObjCStringLiteral,
 TT_UntouchableMacroFunc, TT_StatementAttributeLikeMacro,
-TT_FunctionLikeOrFreestandingMacro, TT_RecordLBrace,
-TT_RequiresClause, TT_RequiresClauseInARequiresExpression,
-TT_RequiresExpression, TT_RequiresExpressionLParen,
-TT_RequiresExpressionLBrace, TT_BinaryOperator,
-TT_CompoundRequirementLBrace, TT_BracedListLBrace))
+TT_FunctionLikeOrFreestandingMa

[clang] 48a31c8 - [clang-format] Mark FormatToken::getPreviousNonComment() nodiscard. NFC.

2022-02-16 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-02-16T22:56:32+01:00
New Revision: 48a31c8f429022a07e2e35f3e62d5f495117f2e7

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

LOG: [clang-format] Mark FormatToken::getPreviousNonComment() nodiscard. NFC.

Added: 


Modified: 
clang/lib/Format/FormatToken.h

Removed: 




diff  --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index 6aaf66c7bb7e..6b7d475232b0 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -693,7 +693,7 @@ struct FormatToken {
   }
 
   /// Returns the previous token ignoring comments.
-  FormatToken *getPreviousNonComment() const {
+  LLVM_NODISCARD FormatToken *getPreviousNonComment() const {
 FormatToken *Tok = Previous;
 while (Tok && Tok->is(tok::comment))
   Tok = Tok->Previous;



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


[clang] ef39235 - [clang-format] Make checking for a record more robust and avoid a loop.

2022-02-16 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-02-16T23:05:49+01:00
New Revision: ef39235cb94289281d610e4df52ad2a746d6af61

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

LOG: [clang-format] Make checking for a record more robust and avoid a loop.

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineFormatter.cpp 
b/clang/lib/Format/UnwrappedLineFormatter.cpp
index 16fa2e7b50f1..dbf1e4cbbf6a 100644
--- a/clang/lib/Format/UnwrappedLineFormatter.cpp
+++ b/clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -312,10 +312,15 @@ class LineJoiner {
   break;
 
   // Check if the found line starts a record.
-  for (const FormatToken *RecordTok = (*J)->Last; RecordTok;
-   RecordTok = RecordTok->Previous)
-if (RecordTok->is(tok::l_brace))
-  return isRecordLBrace(*RecordTok);
+  const FormatToken *LastNonComment = (*J)->Last;
+  assert(LastNonComment);
+  if (LastNonComment->is(tok::comment)) {
+LastNonComment = LastNonComment->getPreviousNonComment();
+// There must be another token (usually `{`), because we chose a
+// line that has a smaller level.
+assert(LastNonComment);
+  }
+  return isRecordLBrace(*LastNonComment);
 }
   }
 

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 6e5dd3284633..73503696741a 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -3809,6 +3809,18 @@ TEST_F(FormatTest, FormatsNamespaces) {
"  }\n"
"} // namespace\n",
ShortInlineFunctions);
+  verifyFormat("namespace { /* comment */\n"
+   "  void f() {\n"
+   "return;\n"
+   "  }\n"
+   "} // namespace\n",
+   ShortInlineFunctions);
+  verifyFormat("namespace { // comment\n"
+   "  void f() {\n"
+   "return;\n"
+   "  }\n"
+   "} // namespace\n",
+   ShortInlineFunctions);
   verifyFormat("namespace {\n"
"  int some_int;\n"
"  void f() {\n"
@@ -3828,6 +3840,18 @@ TEST_F(FormatTest, FormatsNamespaces) {
"  };\n"
"} // namespace\n",
ShortInlineFunctions);
+  verifyFormat("namespace {\n"
+   "  class X { /* comment */\n"
+   "void f() { return; }\n"
+   "  };\n"
+   "} // namespace\n",
+   ShortInlineFunctions);
+  verifyFormat("namespace {\n"
+   "  class X { // comment\n"
+   "void f() { return; }\n"
+   "  };\n"
+   "} // namespace\n",
+   ShortInlineFunctions);
   verifyFormat("namespace {\n"
"  struct X {\n"
"void f() { return; }\n"



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


[clang] 0ae2464 - [clang-format] Fix wrong assertion with non-negative shift when aligning tokens.

2022-02-17 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-02-17T09:49:00+01:00
New Revision: 0ae2464fcd4d2c2f285b83d16ff6e2426dd722d2

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

LOG: [clang-format] Fix wrong assertion with non-negative shift when aligning 
tokens.

Fixes https://github.com/llvm/llvm-project/issues/53880.

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/WhitespaceManager.cpp 
b/clang/lib/Format/WhitespaceManager.cpp
index 758dc5860888e..55e0b7f8e8d9e 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -406,7 +406,7 @@ AlignTokenSequence(const FormatStyle &Style, unsigned 
Start, unsigned End,
   Changes[i].Spaces += Shift;
 
 // We should not remove required spaces unless we break the line before.
-assert(Changes[i].NewlinesBefore > 0 ||
+assert(Shift >= 0 || Changes[i].NewlinesBefore > 0 ||
Changes[i].Spaces >=
static_cast(Changes[i].Tok->SpacesRequiredBefore) ||
Changes[i].Tok->is(tok::eof));

diff  --git a/clang/unittests/Format/FormatTestSelective.cpp 
b/clang/unittests/Format/FormatTestSelective.cpp
index c88d1b8bd8ba2..2725e4cf776f6 100644
--- a/clang/unittests/Format/FormatTestSelective.cpp
+++ b/clang/unittests/Format/FormatTestSelective.cpp
@@ -603,6 +603,14 @@ TEST_F(FormatTestSelective, 
KeepsIndentAfterCommentSectionImport) {
   EXPECT_EQ(Code, format(Code, 47, 1));
 }
 
+TEST_F(FormatTestSelective, DontAssert) {
+  // https://llvm.org/PR53880
+  std::string Code = "void f() {\n"
+ "  return a == 8 ? 32 : 16;\n"
+ "}\n";
+  EXPECT_EQ(Code, format(Code, 40, 0));
+}
+
 } // end namespace
 } // end namespace format
 } // end namespace clang



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


[clang] c819dce - [clang-format] Add a regression test for aligning macros with keywords.

2022-05-03 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-05-03T11:09:38+02:00
New Revision: c819dce2d304817ae7f47628067092f4353a148e

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

LOG: [clang-format] Add a regression test for aligning macros with keywords.

Test from issue https://github.com/llvm/llvm-project/issues/54953.

Added: 


Modified: 
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index da25395b7df49..37f32691a1d36 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -16030,6 +16030,10 @@ TEST_F(FormatTest, AlignConsecutiveMacros) {
"#define ccc  (5)",
Style);
 
+  verifyFormat("#define true  1\n"
+   "#define false 0",
+   Style);
+
   verifyFormat("#define f(x) (x * x)\n"
"#define fff(x, y, z) (x * y + z)\n"
"#define (x, y)   (x - y)",



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


[clang] 50cd52d - [clang-format] Fix WhitespaceSensitiveMacros not being honoured when macro closing parenthesis is followed by a newline.

2022-05-09 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-05-09T10:59:33+02:00
New Revision: 50cd52d9357224cce66a9e00c9a0417c658a5655

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

LOG: [clang-format] Fix WhitespaceSensitiveMacros not being honoured when macro 
closing parenthesis is followed by a newline.

Fixes https://github.com/llvm/llvm-project/issues/54522.

This fixes regression introduced in 
https://github.com/llvm/llvm-project/commit/5e5efd8a91f2e340e79a73bedbc6ab66ad4a4281.

Before the culprit commit, macros in WhitespaceSensitiveMacros were correctly 
formatted even if their closing parenthesis weren't followed by semicolon (or, 
to be precise, when they were followed by a newline).
That commit changed the type of the macro token type from 
TT_UntouchableMacroFunc to TT_FunctionLikeOrFreestandingMacro.

Correct formatting (with `WhitespaceSensitiveMacros = ['FOO']`):
```
FOO(1+2)
FOO(1+2);
```

Regressed formatting:
```
FOO(1 + 2)
FOO(1+2);
```

Reviewed By: HazardyKnusperkeks, owenpan, ksyx

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/FormatTokenLexer.cpp 
b/clang/lib/Format/FormatTokenLexer.cpp
index 187b30fd55a7e..d1d236cf032b2 100644
--- a/clang/lib/Format/FormatTokenLexer.cpp
+++ b/clang/lib/Format/FormatTokenLexer.cpp
@@ -1027,7 +1027,10 @@ FormatToken *FormatTokenLexer::getNextToken() {
   Tokens.back()->Tok.getIdentifierInfo()->getPPKeywordID() ==
   tok::pp_define) &&
 it != Macros.end()) {
-  FormatTok->setType(it->second);
+  if (it->second == TT_UntouchableMacroFunc)
+FormatTok->setFinalizedType(TT_UntouchableMacroFunc);
+  else
+FormatTok->setType(it->second);
   if (it->second == TT_IfMacro) {
 // The lexer token currently has type tok::kw_unknown. However, for 
this
 // substitution to be treated correctly in the TokenAnnotator, faking

diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 52ce0fff251c2..f13e3d725cbd3 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -1787,7 +1787,8 @@ void 
UnwrappedLineParser::parseStructuralElement(IfStmtKind *IfKind,
 : CommentsBeforeNextToken.front()->NewlinesBefore > 0;
 
 if (FollowedByNewline && (Text.size() >= 5 || FunctionLike) &&
-tokenCanStartNewLine(*FormatTok) && Text == Text.upper()) {
+tokenCanStartNewLine(*FormatTok) && Text == Text.upper() &&
+!PreviousToken->isTypeFinalized()) {
   PreviousToken->setFinalizedType(TT_FunctionLikeOrFreestandingMacro);
   addUnwrappedLine();
   return;

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index d7d69f950a323..98da4f773de95 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -23606,6 +23606,11 @@ TEST_F(FormatTest, WhitespaceSensitiveMacros) {
 
   // Don't use the helpers here, since 'mess up' will change the whitespace
   // and these are all whitespace sensitive by definition
+
+  // Newlines are important here.
+  EXPECT_EQ("FOO(1+2  );\n", format("FOO(1+2  );\n", Style));
+  EXPECT_EQ("FOO(1+2  )\n", format("FOO(1+2  )\n", Style));
+
   EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);",
 format("FOO(String-ized&Messy+But(: :Still)=Intentional);", 
Style));
   EXPECT_EQ(



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


[clang] 85ec8a9 - [clang-format] Correctly handle SpaceBeforeParens for builtins.

2022-05-09 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-05-09T11:42:41+02:00
New Revision: 85ec8a9ac141a1807d907b7514546f531007d87d

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

LOG: [clang-format] Correctly handle SpaceBeforeParens for builtins.

That's a partial fix for https://github.com/llvm/llvm-project/issues/55292.

Before, known builtins behaved differently from other identifiers:
```
void f () { return F (__builtin_LINE() + __builtin_FOO ()); }
```
After:
```
void f () { return F (__builtin_LINE () + __builtin_FOO ()); }
```

Reviewed By: owenpan

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 8cbe157b1fb21..68f35643bbf2f 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3436,9 +3436,9 @@ bool TokenAnnotator::spaceRequiredBetween(const 
AnnotatedLine &Line,
 return (Style.SpaceBeforeParens != FormatStyle::SBPO_Never) ||
spaceRequiredBeforeParens(Right);
 }
+// Handle builtins like identifiers.
 if (Line.Type != LT_PreprocessorDirective &&
-(Left.is(tok::identifier) || Left.isFunctionLikeKeyword() ||
- Left.is(tok::r_paren) || Left.isSimpleTypeSpecifier()))
+(Left.Tok.getIdentifierInfo() || Left.is(tok::r_paren)))
   return spaceRequiredBeforeParens(Right);
 return false;
   }

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 98da4f773de95..78f7eee809c4d 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -15082,6 +15082,9 @@ TEST_F(FormatTest, ConfigurableSpaceBeforeParens) {
   // verifyFormat("X A::operator++ (T);", Space);
   verifyFormat("auto lambda = [] () { return 0; };", Space);
   verifyFormat("int x = int (y);", Space);
+  verifyFormat("#define F(...) __VA_OPT__ (__VA_ARGS__)", Space);
+  verifyFormat("__builtin_LINE ()", Space);
+  verifyFormat("__builtin_UNKNOWN ()", Space);
 
   FormatStyle SomeSpace = getLLVMStyle();
   SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses;



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


[clang] dab5e10 - [clang-format] fix nested angle brackets parse inside concept definition

2022-05-11 Thread Marek Kurdej via cfe-commits

Author: Sergey Semushin
Date: 2022-05-11T14:02:51+02:00
New Revision: dab5e10ea5dbc2e6314e0e7ce54a9c51fbcb44bd

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

LOG: [clang-format] fix nested angle brackets parse inside concept definition

Due to how parseBracedList always stopped on the first closing angle
bracket and was used in parsing angle bracketed expression inside concept
definition, nested brackets inside concepts were parsed incorrectly.

nextToken() call before calling parseBracedList is required because
we were processing opening angle bracket inside parseBracedList second
time leading to incorrect logic after my fix.

Fixes https://github.com/llvm/llvm-project/issues/54943
Fixes https://github.com/llvm/llvm-project/issues/54837

Reviewed By: HazardyKnusperkeks, curdeius

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index f13e3d725cbd3..f90e8fcb834c7 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -2180,7 +2180,8 @@ bool UnwrappedLineParser::parseBracedList(bool 
ContinueOnSemicolons,
   parseBracedList();
   break;
 case tok::less:
-  if (Style.Language == FormatStyle::LK_Proto) {
+  if (Style.Language == FormatStyle::LK_Proto ||
+  ClosingBraceKind == tok::greater) {
 nextToken();
 parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false,
 /*ClosingBraceKind=*/tok::greater);
@@ -3220,6 +3221,7 @@ void UnwrappedLineParser::parseConstraintExpression() {
   if (!FormatTok->is(tok::less))
 return;
 
+  nextToken();
   parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false,
   /*ClosingBraceKind=*/tok::greater);
   break;
@@ -3260,9 +3262,11 @@ void UnwrappedLineParser::parseConstraintExpression() {
 
   // Read identifier with optional template declaration.
   nextToken();
-  if (FormatTok->is(tok::less))
+  if (FormatTok->is(tok::less)) {
+nextToken();
 parseBracedList(/*ContinueOnSemicolons=*/false, /*IsEnum=*/false,
 /*ClosingBraceKind=*/tok::greater);
+  }
   break;
 }
   } while (!eof());

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 78f7eee809c4d..8f9c7215d6193 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -24114,6 +24114,12 @@ TEST_F(FormatTest, Concepts) {
   verifyFormat("template \n"
"concept Same = __is_same_as;");
 
+  verifyFormat(
+  "template \n"
+  "concept _Can_reread_dest =\n"
+  "std::forward_iterator<_OutIt> &&\n"
+  "std::same_as, 
std::iter_value_t<_OutIt>>;");
+
   auto Style = getLLVMStyle();
   Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Allowed;
 

diff  --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 3d2c3a498c724..138cab9b6b257 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -390,6 +390,18 @@ TEST_F(TokenAnnotatorTest, 
UnderstandsRequiresClausesAndConcepts) {
   EXPECT_TOKEN(Tokens[21], tok::r_brace, TT_Unknown);
   EXPECT_EQ(Tokens[21]->MatchingParen, Tokens[15]);
   EXPECT_TRUE(Tokens[21]->ClosesRequiresClause);
+
+  Tokens =
+  annotate("template  concept C ="
+   "std::same_as, std::iter_value_t>;");
+  ASSERT_EQ(Tokens.size(), 31u) << Tokens;
+  EXPECT_TOKEN(Tokens[8], tok::kw_concept, TT_Unknown);
+  EXPECT_TOKEN(Tokens[14], tok::less, TT_TemplateOpener);
+  EXPECT_TOKEN(Tokens[18], tok::less, TT_TemplateOpener);
+  EXPECT_TOKEN(Tokens[20], tok::greater, TT_TemplateCloser);
+  EXPECT_TOKEN(Tokens[25], tok::less, TT_TemplateOpener);
+  EXPECT_TOKEN(Tokens[27], tok::greater, TT_TemplateCloser);
+  EXPECT_TOKEN(Tokens[28], tok::greater, TT_TemplateCloser);
 }
 
 TEST_F(TokenAnnotatorTest, UnderstandsRequiresExpressions) {



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


[clang] e20bc89 - [clang-format] Fix PointerAlignment: Right not working with tab indentation.

2022-05-16 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-05-16T09:42:20+02:00
New Revision: e20bc892b6facc56fffc012929157888bb798bed

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

LOG: [clang-format] Fix PointerAlignment: Right not working with tab 
indentation.

Fixes https://github.com/llvm/llvm-project/issues/55407.

Given configuration:
```
UseTab: Always
PointerAlignment: Right
AlignConsecutiveDeclarations: true
```

Before, the pointer was misaligned in this code:
```
void f() {
unsigned long long big;
char  *ptr; // misaligned
inti;
}
```

That was due to the fact that when handling right-aligned pointers, the Spaces 
were changed but StartOfTokenColumn was not.

Also, a tab was used not only for indentation but for spacing too when using 
`UseTab: ForIndentation` config option:
```
void f() {
unsigned long long big;
char  *ptr; // \t after char
inti;
}
```

Reviewed By: owenpan

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/WhitespaceManager.cpp 
b/clang/lib/Format/WhitespaceManager.cpp
index 8563312b45bb0..673af51d2daae 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -432,6 +432,7 @@ AlignTokenSequence(const FormatStyle &Style, unsigned 
Start, unsigned End,
--Previous) {
 Changes[Previous + 1].Spaces -= Shift;
 Changes[Previous].Spaces += Shift;
+Changes[Previous].StartOfTokenColumn += Shift;
   }
 }
   }

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index e4fea9085b574..44da34001f990 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -14161,6 +14161,21 @@ TEST_F(FormatTest, ConfigurableUseOfTab) {
"int ; // x\n",
Tab);
 
+  FormatStyle TabAlignment = Tab;
+  TabAlignment.AlignConsecutiveDeclarations.Enabled = true;
+  TabAlignment.PointerAlignment = FormatStyle::PAS_Left;
+  verifyFormat("unsigned long long big;\n"
+   "char*\t\t   ptr;",
+   TabAlignment);
+  TabAlignment.PointerAlignment = FormatStyle::PAS_Middle;
+  verifyFormat("unsigned long long big;\n"
+   "char *\t\t   ptr;",
+   TabAlignment);
+  TabAlignment.PointerAlignment = FormatStyle::PAS_Right;
+  verifyFormat("unsigned long long big;\n"
+   "char\t\t  *ptr;",
+   TabAlignment);
+
   Tab.TabWidth = 4;
   Tab.IndentWidth = 8;
   verifyFormat("class TabWidth4Indent8 {\n"
@@ -14203,6 +14218,26 @@ TEST_F(FormatTest, ConfigurableUseOfTab) {
" \t  */",
Tab));
 
+  TabAlignment.UseTab = FormatStyle::UT_ForIndentation;
+  TabAlignment.PointerAlignment = FormatStyle::PAS_Left;
+  verifyFormat("void f() {\n"
+   "\tunsigned long long big;\n"
+   "\tchar*  ptr;\n"
+   "}",
+   TabAlignment);
+  TabAlignment.PointerAlignment = FormatStyle::PAS_Middle;
+  verifyFormat("void f() {\n"
+   "\tunsigned long long big;\n"
+   "\tchar * ptr;\n"
+   "}",
+   TabAlignment);
+  TabAlignment.PointerAlignment = FormatStyle::PAS_Right;
+  verifyFormat("void f() {\n"
+   "\tunsigned long long big;\n"
+   "\tchar  *ptr;\n"
+   "}",
+   TabAlignment);
+
   Tab.UseTab = FormatStyle::UT_ForIndentation;
   verifyFormat("{\n"
"\t();\n"



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


[clang] e57f578 - [clang-format] fix alignment w/o binpacked args

2022-05-16 Thread Marek Kurdej via cfe-commits

Author: Gregory Fong
Date: 2022-05-16T10:25:06+02:00
New Revision: e57f57841fbb0cd1d1dbd3237c2cbe6ce15984dd

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

LOG: [clang-format] fix alignment w/o binpacked args

The combination of

- AlignConsecutiveAssignments.Enabled = true
- BinPackArguments = false

would result in the first continuation line of a braced-init-list being
improperly indented (missing a shift) when in a continued function call.
Indentation was also wrong for braced-init-lists continuing a
direct-list-initialization.  Check for opening braced lists in
continuation and ensure that the correct shift occurs.

Fixes https://github.com/llvm/llvm-project/issues/55360

Reviewed By: curdeius

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/WhitespaceManager.cpp 
b/clang/lib/Format/WhitespaceManager.cpp
index 673af51d2daa..f20383800ab4 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -371,6 +371,9 @@ AlignTokenSequence(const FormatStyle &Style, unsigned 
Start, unsigned End,
 return false;
   if (Changes[ScopeStart].NewlinesBefore > 0)
 return false;
+  if (Changes[i].Tok->is(tok::l_brace) &&
+  Changes[i].Tok->is(BK_BracedInit))
+return true;
   return Style.BinPackArguments;
 }
 
@@ -387,6 +390,14 @@ AlignTokenSequence(const FormatStyle &Style, unsigned 
Start, unsigned End,
 Changes[i].Tok->Previous->is(TT_ConditionalExpr))
   return true;
 
+// Continued direct-list-initialization using braced list.
+if (ScopeStart > Start + 1 &&
+Changes[ScopeStart - 2].Tok->is(tok::identifier) &&
+Changes[ScopeStart - 1].Tok->is(tok::l_brace) &&
+Changes[i].Tok->is(tok::l_brace) &&
+Changes[i].Tok->is(BK_BracedInit))
+  return true;
+
 // Continued braced list.
 if (ScopeStart > Start + 1 &&
 Changes[ScopeStart - 2].Tok->isNot(tok::identifier) &&

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 44da34001f99..22c46a129403 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -17318,6 +17318,23 @@ TEST_F(FormatTest, AlignConsecutiveAssignments) {
   //  "ccc ? a : b,\n"
   //  "dd);",
   //  Alignment);
+
+  // Confirm proper handling of AlignConsecutiveAssignments with
+  // BinPackArguments.
+  // See https://llvm.org/PR55360
+  Alignment = getLLVMStyleWithColumns(50);
+  Alignment.AlignConsecutiveAssignments.Enabled = true;
+  Alignment.BinPackArguments = false;
+  verifyFormat("int a_long_name = 1;\n"
+   "auto b  = B({a_long_name, a_long_name},\n"
+   "{a_longer_name_for_wrap,\n"
+   " a_longer_name_for_wrap});",
+   Alignment);
+  verifyFormat("int a_long_name = 1;\n"
+   "auto b  = B{{a_long_name, a_long_name},\n"
+   "{a_longer_name_for_wrap,\n"
+   " a_longer_name_for_wrap}};",
+   Alignment);
 }
 
 TEST_F(FormatTest, AlignConsecutiveBitFields) {



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


[clang] 573a5b5 - Revert "[clang-format] Fix WhitespaceSensitiveMacros not being honoured when macro closing parenthesis is followed by a newline."

2022-05-17 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-05-18T07:27:45+02:00
New Revision: 573a5b58001d6dd86d404832b7b1c45a1b4f4c55

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

LOG: Revert "[clang-format] Fix WhitespaceSensitiveMacros not being honoured 
when macro closing parenthesis is followed by a newline."

This reverts commit 50cd52d9357224cce66a9e00c9a0417c658a5655.

It provoked regressions in C++ and ObjectiveC as described in 
https://reviews.llvm.org/D123676#3515949.

Reproducers:
```
MACRO_BEGIN
#if A
int f();
#else
int f();
#endif
```

```
NS_SWIFT_NAME(A)
@interface B : C
@property(readonly) D value;
@end
```

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/FormatTokenLexer.cpp 
b/clang/lib/Format/FormatTokenLexer.cpp
index d1d236cf032b2..187b30fd55a7e 100644
--- a/clang/lib/Format/FormatTokenLexer.cpp
+++ b/clang/lib/Format/FormatTokenLexer.cpp
@@ -1027,10 +1027,7 @@ FormatToken *FormatTokenLexer::getNextToken() {
   Tokens.back()->Tok.getIdentifierInfo()->getPPKeywordID() ==
   tok::pp_define) &&
 it != Macros.end()) {
-  if (it->second == TT_UntouchableMacroFunc)
-FormatTok->setFinalizedType(TT_UntouchableMacroFunc);
-  else
-FormatTok->setType(it->second);
+  FormatTok->setType(it->second);
   if (it->second == TT_IfMacro) {
 // The lexer token currently has type tok::kw_unknown. However, for 
this
 // substitution to be treated correctly in the TokenAnnotator, faking

diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index bde543131931e..be081a9189600 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -1839,8 +1839,7 @@ void 
UnwrappedLineParser::parseStructuralElement(IfStmtKind *IfKind,
 : CommentsBeforeNextToken.front()->NewlinesBefore > 0;
 
 if (FollowedByNewline && (Text.size() >= 5 || FunctionLike) &&
-tokenCanStartNewLine(*FormatTok) && Text == Text.upper() &&
-!PreviousToken->isTypeFinalized()) {
+tokenCanStartNewLine(*FormatTok) && Text == Text.upper()) {
   PreviousToken->setFinalizedType(TT_FunctionLikeOrFreestandingMacro);
   addUnwrappedLine();
   return;

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 22c46a129403b..e54a6db2ca46b 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -23661,11 +23661,6 @@ TEST_F(FormatTest, WhitespaceSensitiveMacros) {
 
   // Don't use the helpers here, since 'mess up' will change the whitespace
   // and these are all whitespace sensitive by definition
-
-  // Newlines are important here.
-  EXPECT_EQ("FOO(1+2  );\n", format("FOO(1+2  );\n", Style));
-  EXPECT_EQ("FOO(1+2  )\n", format("FOO(1+2  )\n", Style));
-
   EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);",
 format("FOO(String-ized&Messy+But(: :Still)=Intentional);", 
Style));
   EXPECT_EQ(



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


[clang] 6627a3c - [c++2b] Add option -std=c++2b to enable support for potential C++2b features.

2020-12-03 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2020-12-03T10:27:47+01:00
New Revision: 6627a3c2873fdf7ccba1a1573371079be48b36e8

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

LOG: [c++2b] Add option -std=c++2b to enable support for potential C++2b 
features.

Reviewed By: rsmith

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

Added: 


Modified: 
clang/include/clang/Basic/LangOptions.def
clang/include/clang/Basic/LangStandard.h
clang/include/clang/Basic/LangStandards.def
clang/lib/Frontend/CompilerInvocation.cpp
clang/lib/Frontend/InitPreprocessor.cpp
clang/test/Driver/std.cpp
clang/test/Driver/unknown-std.cpp
clang/test/Preprocessor/init.c

Removed: 




diff  --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index 071cc314b7d1..19fb4ae82b89 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -92,6 +92,7 @@ LANGOPT(CPlusPlus11   , 1, 0, "C++11")
 LANGOPT(CPlusPlus14   , 1, 0, "C++14")
 LANGOPT(CPlusPlus17   , 1, 0, "C++17")
 LANGOPT(CPlusPlus20   , 1, 0, "C++20")
+LANGOPT(CPlusPlus2b   , 1, 0, "C++2b")
 LANGOPT(ObjC  , 1, 0, "Objective-C")
 BENIGN_LANGOPT(ObjCDefaultSynthProperties , 1, 0,
"Objective-C auto-synthesized properties")

diff  --git a/clang/include/clang/Basic/LangStandard.h 
b/clang/include/clang/Basic/LangStandard.h
index ad7f7510b234..f82ce05a6369 100644
--- a/clang/include/clang/Basic/LangStandard.h
+++ b/clang/include/clang/Basic/LangStandard.h
@@ -49,11 +49,12 @@ enum LangFeatures {
   CPlusPlus14 = (1 << 7),
   CPlusPlus17 = (1 << 8),
   CPlusPlus20 = (1 << 9),
-  Digraphs = (1 << 10),
-  GNUMode = (1 << 11),
-  HexFloat = (1 << 12),
-  ImplicitInt = (1 << 13),
-  OpenCL = (1 << 14)
+  CPlusPlus2b = (1 << 10),
+  Digraphs = (1 << 11),
+  GNUMode = (1 << 12),
+  HexFloat = (1 << 13),
+  ImplicitInt = (1 << 14),
+  OpenCL = (1 << 15)
 };
 
 /// LangStandard - Information about the properties of a particular language
@@ -111,6 +112,9 @@ struct LangStandard {
   /// isCPlusPlus20 - Language is a C++20 variant (or later).
   bool isCPlusPlus20() const { return Flags & CPlusPlus20; }
 
+  /// isCPlusPlus2b - Language is a post-C++20 variant (or later).
+  bool isCPlusPlus2b() const { return Flags & CPlusPlus2b; }
+
   /// hasDigraphs - Language supports digraphs.
   bool hasDigraphs() const { return Flags & Digraphs; }
 

diff  --git a/clang/include/clang/Basic/LangStandards.def 
b/clang/include/clang/Basic/LangStandards.def
index 7b915c312746..f086d8a43ccb 100644
--- a/clang/include/clang/Basic/LangStandards.def
+++ b/clang/include/clang/Basic/LangStandards.def
@@ -152,6 +152,16 @@ LANGSTANDARD(gnucxx20, "gnu++20",
  CPlusPlus20 | Digraphs | HexFloat | GNUMode)
 LANGSTANDARD_ALIAS_DEPR(gnucxx20, "gnu++2a")
 
+LANGSTANDARD(cxx2b, "c++2b",
+ CXX, "Working draft for ISO C++ 2023 DIS",
+ LineComment | CPlusPlus | CPlusPlus11 | CPlusPlus14 | CPlusPlus17 
|
+ CPlusPlus20 | CPlusPlus2b | Digraphs | HexFloat)
+
+LANGSTANDARD(gnucxx2b, "gnu++2b",
+ CXX, "Working draft for ISO C++ 2023 DIS with GNU extensions",
+ LineComment | CPlusPlus | CPlusPlus11 | CPlusPlus14 | CPlusPlus17 
|
+ CPlusPlus20 | CPlusPlus2b | Digraphs | HexFloat | GNUMode)
+
 // OpenCL
 LANGSTANDARD(opencl10, "cl1.0",
  OpenCL, "OpenCL 1.0",

diff  --git a/clang/lib/Frontend/CompilerInvocation.cpp 
b/clang/lib/Frontend/CompilerInvocation.cpp
index 1c63ce612be0..e31f6aa34b36 100644
--- a/clang/lib/Frontend/CompilerInvocation.cpp
+++ b/clang/lib/Frontend/CompilerInvocation.cpp
@@ -2388,6 +2388,7 @@ void CompilerInvocation::setLangDefaults(LangOptions 
&Opts, InputKind IK,
   Opts.CPlusPlus14 = Std.isCPlusPlus14();
   Opts.CPlusPlus17 = Std.isCPlusPlus17();
   Opts.CPlusPlus20 = Std.isCPlusPlus20();
+  Opts.CPlusPlus2b = Std.isCPlusPlus2b();
   Opts.Digraphs = Std.hasDigraphs();
   Opts.GNUMode = Std.isGNUMode();
   Opts.GNUInline = !Opts.C99 && !Opts.CPlusPlus;

diff  --git a/clang/lib/Frontend/InitPreprocessor.cpp 
b/clang/lib/Frontend/InitPreprocessor.cpp
index 86d5e61b7112..42eed9f6c7b5 100644
--- a/clang/lib/Frontend/InitPreprocessor.cpp
+++ b/clang/lib/Frontend/InitPreprocessor.cpp
@@ -376,8 +376,11 @@ static void InitializeStandardPredefinedMacros(const 
TargetInfo &TI,
   Builder.defineMacro("__STDC_VERSION__", "199409L");
   } else {
 //   -- __cplusplus
+// FIXME: Use correct value for C++23.
+if (LangOpts.CPlusPlus2b)
+  Builder.defineMacro("__cplusplus", "202101L");
 //  [C++20] The integer literal 202002L.
-if (LangOpts.CPlusPlus20)
+else if (LangOpts.CPlusPlus20)
   Builder.defineMacro("__cplusplu

[clang] fe21c86 - [clang-format] De-duplicate includes with leading or trailing whitespace.

2020-12-03 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2020-12-03T10:59:46+01:00
New Revision: fe21c86ee75f93bb0372660c004ac2325ac12cdc

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

LOG: [clang-format] De-duplicate includes with leading or trailing whitespace.

This fixes PR46555 (https://bugs.llvm.org/show_bug.cgi?id=46555).

Reviewed By: MyDeveloperDay

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

Added: 


Modified: 
clang/lib/Format/Format.cpp
clang/unittests/Format/SortIncludesTest.cpp

Removed: 




diff  --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index 235621c4f9aa8..6f96395f608d2 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -2179,7 +2179,8 @@ static void sortCppIncludes(const FormatStyle &Style,
   // Deduplicate #includes.
   Indices.erase(std::unique(Indices.begin(), Indices.end(),
 [&](unsigned LHSI, unsigned RHSI) {
-  return Includes[LHSI].Text == 
Includes[RHSI].Text;
+  return Includes[LHSI].Text.trim() ==
+ Includes[RHSI].Text.trim();
 }),
 Indices.end());
 

diff  --git a/clang/unittests/Format/SortIncludesTest.cpp 
b/clang/unittests/Format/SortIncludesTest.cpp
index 279c4ee15a10c..cb2d2bd782fc8 100644
--- a/clang/unittests/Format/SortIncludesTest.cpp
+++ b/clang/unittests/Format/SortIncludesTest.cpp
@@ -289,6 +289,19 @@ TEST_F(SortIncludesTest, LeadingWhitespace) {
 sort("# include \"a.h\"\n"
  "#  include \"c.h\"\n"
  "#   include \"b.h\"\n"));
+  EXPECT_EQ("#include \"a.h\"\n", sort("#include \"a.h\"\n"
+   " #include \"a.h\"\n"));
+}
+
+TEST_F(SortIncludesTest, TrailingWhitespace) {
+  EXPECT_EQ("#include \"a.h\"\n"
+"#include \"b.h\"\n"
+"#include \"c.h\"\n",
+sort("#include \"a.h\" \n"
+ "#include \"c.h\"  \n"
+ "#include \"b.h\"   \n"));
+  EXPECT_EQ("#include \"a.h\"\n", sort("#include \"a.h\"\n"
+   "#include \"a.h\" \n"));
 }
 
 TEST_F(SortIncludesTest, GreaterInComment) {



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


[clang] 8702c6d - [clang-format] [docs] Regenerate style options documentation.

2021-05-28 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2021-05-28T21:48:36+02:00
New Revision: 8702c6da162b6db962c8155195d79f1e002bc481

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

LOG: [clang-format] [docs] Regenerate style options documentation.

Forgotten in commits fce8c10b, 9363aa90, 8d93d7ff.

Added: 


Modified: 
clang/docs/ClangFormatStyleOptions.rst

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 986963c8ce67c..459887705d4ec 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -773,7 +773,7 @@ the configuration (without a prefix: ``Auto``).
 
 
 **AllowShortIfStatementsOnASingleLine** (``ShortIfStyle``)
-  If ``true``, ``if (a) return;`` can be put on a single line.
+  Dependent on the value, ``if (a) return;`` can be put on a single line.
 
   Possible values:
 
@@ -783,28 +783,67 @@ the configuration (without a prefix: ``Auto``).
 .. code-block:: c++
 
   if (a)
-return ;
+return;
+
+  if (b)
+return;
+  else
+return;
+
+  if (c)
+return;
   else {
 return;
   }
 
   * ``SIS_WithoutElse`` (in configuration: ``WithoutElse``)
-Without else put short ifs on the same line only if
-the else is not a compound statement.
+Put short ifs on the same line only if there is no else statement.
 
 .. code-block:: c++
 
   if (a) return;
+
+  if (b)
+return;
   else
 return;
 
-  * ``SIS_Always`` (in configuration: ``Always``)
-Always put short ifs on the same line if
-the else is not a compound statement or not.
+  if (c)
+return;
+  else {
+return;
+  }
+
+  * ``SIS_OnlyFirstIf`` (in configuration: ``OnlyFirstIf``)
+Put short ifs, but not else ifs nor else statements, on the same line.
 
 .. code-block:: c++
 
   if (a) return;
+
+  if (b) return;
+  else if (b)
+return;
+  else
+return;
+
+  if (c) return;
+  else {
+return;
+  }
+
+  * ``SIS_AllIfsAndElse`` (in configuration: ``AllIfsAndElse``)
+Always put short ifs, else ifs and else statements on the same
+line.
+
+.. code-block:: c++
+
+  if (a) return;
+
+  if (b) return;
+  else return;
+
+  if (c) return;
   else {
 return;
   }
@@ -2176,8 +2215,11 @@ the configuration (without a prefix: ``Auto``).
   private:
 
   protected:
+
   };
 
+
+
 **EmptyLineBeforeAccessModifier** (``EmptyLineBeforeAccessModifierStyle``)
   Defines in which cases to put empty line before access modifiers.
 
@@ -2245,6 +2287,8 @@ the configuration (without a prefix: ``Auto``).
   protected:
   };
 
+
+
 **ExperimentalAutoDetectBinPacking** (``bool``)
   If ``true``, clang-format detects whether function calls and
   definitions are formatted with one parameter per line.
@@ -3441,15 +3485,32 @@ the configuration (without a prefix: ``Auto``).
} // foo
  }
 
-**SpacesInAngles** (``bool``)
-  If ``true``, spaces will be inserted after ``<`` and before ``>``
-  in template argument lists.
+**SpacesInAngles** (``SpacesInAnglesStyle``)
+  The SpacesInAnglesStyle to use for template argument lists.
+
+  Possible values:
+
+  * ``SIAS_Never`` (in configuration: ``Never``)
+Remove spaces after ``<`` and before ``>``.
+
+.. code-block:: c++
+
+   static_cast(arg);
+   std::function fct;
+
+  * ``SIAS_Always`` (in configuration: ``Always``)
+Add spaces after ``<`` and before ``>``.
+
+.. code-block:: c++
+
+   static_cast< int >(arg);
+   std::function< void(int) > fct;
+
+  * ``SIAS_Leave`` (in configuration: ``Leave``)
+Keep a single space after ``<`` and before ``>`` if any spaces were
+present. Option ``Standard: Cpp03`` takes precedence.
 
-  .. code-block:: c++
 
- true:  false:
- static_cast< int >(arg);   vs. static_cast(arg);
- std::function< void(int) > fct;std::function fct;
 
 **SpacesInCStyleCastParentheses** (``bool``)
   If ``true``, spaces may be inserted into C style casts.



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


[clang] f00a20e - [clang-format] Add the possibility to align assignments spanning empty lines or comments

2021-01-25 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2021-01-25T09:36:55+01:00
New Revision: f00a20e51c1d186e72844939aad10416e1cc99de

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

LOG: [clang-format] Add the possibility to align assignments spanning empty 
lines or comments

Currently, empty lines and comments break alignment of assignments on 
consecutive
lines. This makes the AlignConsecutiveAssignments option an enum that allows 
controlling
whether empty lines or empty lines and comments should be ignored when aligning
assignments.

Reviewed By: MyDeveloperDay, HazardyKnusperkeks, tinloaf

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

Added: 


Modified: 
clang/docs/ClangFormatStyleOptions.rst
clang/docs/ReleaseNotes.rst
clang/docs/tools/dump_format_style.py
clang/include/clang/Format/Format.h
clang/lib/Format/Format.cpp
clang/lib/Format/WhitespaceManager.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 27dcee83a538..6877cac28278 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -195,23 +195,84 @@ the configuration (without a prefix: ``Auto``).
 
 
 
-**AlignConsecutiveAssignments** (``bool``)
-  If ``true``, aligns consecutive assignments.
+**AlignConsecutiveAssignments** (``AlignConsecutiveStyle``)
+  Style of aligning consecutive assignments.
 
-  This will align the assignment operators of consecutive lines. This
-  will result in formattings like
+  ``Consecutive`` will result in formattings like:
 
   .. code-block:: c++
 
-int  = 12;
-int b= 23;
-int ccc  = 23;
+int a= 1;
+int somelongname = 2;
+double c = 3;
 
-**AlignConsecutiveBitFields** (``bool``)
-  If ``true``, aligns consecutive bitfield members.
+  Possible values:
+
+  * ``ACS_None`` (in configuration: ``None``)
+ Do not align assignments on consecutive lines.
+
+  * ``ACS_Consecutive`` (in configuration: ``Consecutive``)
+ Align assignments on consecutive lines. This will result in
+ formattings like:
+
+ .. code-block:: c++
+
+   int a= 1;
+   int somelongname = 2;
+   double c = 3;
+
+   int d = 3;
+   /* A comment. */
+   double e = 4;
+
+  * ``ACS_AcrossEmptyLines`` (in configuration: ``AcrossEmptyLines``)
+ Same as ACS_Consecutive, but also spans over empty lines, e.g.
+
+ .. code-block:: c++
+
+   int a= 1;
+   int somelongname = 2;
+   double c = 3;
+
+   int d= 3;
+   /* A comment. */
+   double e = 4;
+
+  * ``ACS_AcrossComments`` (in configuration: ``AcrossComments``)
+ Same as ACS_Consecutive, but also spans over lines only containing
+ comments, e.g.
+
+ .. code-block:: c++
+
+   int a= 1;
+   int somelongname = 2;
+   double c = 3;
+
+   int d= 3;
+   /* A comment. */
+   double e = 4;
+
+  * ``ACS_AcrossEmptyLinesAndComments``
+(in configuration: ``AcrossEmptyLinesAndComments``)
+
+ Same as ACS_Consecutive, but also spans over lines only containing
+ comments and empty lines, e.g.
+
+ .. code-block:: c++
+
+   int a= 1;
+   int somelongname = 2;
+   double c = 3;
+
+   int d= 3;
+   /* A comment. */
+   double e = 4;
+
+**AlignConsecutiveBitFields** (``AlignConsecutiveStyle``)
+  Style of aligning consecutive bit field.
 
-  This will align the bitfield separators of consecutive lines. This
-  will result in formattings like
+  ``Consecutive`` will align the bitfield separators of consecutive lines.
+  This will result in formattings like:
 
   .. code-block:: c++
 
@@ -219,23 +280,146 @@ the configuration (without a prefix: ``Auto``).
 int b: 12;
 int ccc  : 8;
 
-**AlignConsecutiveDeclarations** (``bool``)
-  If ``true``, aligns consecutive declarations.
+  Possible values:
+
+  * ``ACS_None`` (in configuration: ``None``)
+ Do not align bit fields on consecutive lines.
+
+  * ``ACS_Consecutive`` (in configuration: ``Consecutive``)
+ Align bit fields on consecutive lines. This will result in
+ formattings like:
+
+ .. code-block:: c++
+
+   int  : 1;
+   int b: 12;
+   int ccc  : 8;
+
+   int d : 2;
+   /* A comment. */
+   int ee : 3;
+
+  * ``ACS_AcrossEmptyLines`` (in configuration: ``AcrossEmptyLines``)
+ Same as ACS_Consecutive, but also spans over empty lines, e.g.
+
+ .. code-block:: c++
+
+   int  : 1;
+   int b: 12;
+   int ccc  : 8;
+
+   int d: 2;
+   /* A comment. */
+   int ee : 3;
+
+  * ``ACS_Acro

[clang] 7b9d88a - Revert "[clang-format] Add the possibility to align assignments spanning empty lines or comments"

2021-01-25 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2021-01-25T09:40:46+01:00
New Revision: 7b9d88ab389e19d26432b1c1a6d57f554feb9a20

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

LOG: Revert "[clang-format] Add the possibility to align assignments spanning 
empty lines or comments"

This reverts commit f00a20e51c1d186e72844939aad10416e1cc99de.

Added: 


Modified: 
clang/docs/ClangFormatStyleOptions.rst
clang/docs/ReleaseNotes.rst
clang/docs/tools/dump_format_style.py
clang/include/clang/Format/Format.h
clang/lib/Format/Format.cpp
clang/lib/Format/WhitespaceManager.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 6877cac28278..27dcee83a538 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -195,84 +195,23 @@ the configuration (without a prefix: ``Auto``).
 
 
 
-**AlignConsecutiveAssignments** (``AlignConsecutiveStyle``)
-  Style of aligning consecutive assignments.
+**AlignConsecutiveAssignments** (``bool``)
+  If ``true``, aligns consecutive assignments.
 
-  ``Consecutive`` will result in formattings like:
+  This will align the assignment operators of consecutive lines. This
+  will result in formattings like
 
   .. code-block:: c++
 
-int a= 1;
-int somelongname = 2;
-double c = 3;
+int  = 12;
+int b= 23;
+int ccc  = 23;
 
-  Possible values:
-
-  * ``ACS_None`` (in configuration: ``None``)
- Do not align assignments on consecutive lines.
-
-  * ``ACS_Consecutive`` (in configuration: ``Consecutive``)
- Align assignments on consecutive lines. This will result in
- formattings like:
-
- .. code-block:: c++
-
-   int a= 1;
-   int somelongname = 2;
-   double c = 3;
-
-   int d = 3;
-   /* A comment. */
-   double e = 4;
-
-  * ``ACS_AcrossEmptyLines`` (in configuration: ``AcrossEmptyLines``)
- Same as ACS_Consecutive, but also spans over empty lines, e.g.
-
- .. code-block:: c++
-
-   int a= 1;
-   int somelongname = 2;
-   double c = 3;
-
-   int d= 3;
-   /* A comment. */
-   double e = 4;
-
-  * ``ACS_AcrossComments`` (in configuration: ``AcrossComments``)
- Same as ACS_Consecutive, but also spans over lines only containing
- comments, e.g.
-
- .. code-block:: c++
-
-   int a= 1;
-   int somelongname = 2;
-   double c = 3;
-
-   int d= 3;
-   /* A comment. */
-   double e = 4;
-
-  * ``ACS_AcrossEmptyLinesAndComments``
-(in configuration: ``AcrossEmptyLinesAndComments``)
-
- Same as ACS_Consecutive, but also spans over lines only containing
- comments and empty lines, e.g.
-
- .. code-block:: c++
-
-   int a= 1;
-   int somelongname = 2;
-   double c = 3;
-
-   int d= 3;
-   /* A comment. */
-   double e = 4;
-
-**AlignConsecutiveBitFields** (``AlignConsecutiveStyle``)
-  Style of aligning consecutive bit field.
+**AlignConsecutiveBitFields** (``bool``)
+  If ``true``, aligns consecutive bitfield members.
 
-  ``Consecutive`` will align the bitfield separators of consecutive lines.
-  This will result in formattings like:
+  This will align the bitfield separators of consecutive lines. This
+  will result in formattings like
 
   .. code-block:: c++
 
@@ -280,146 +219,23 @@ the configuration (without a prefix: ``Auto``).
 int b: 12;
 int ccc  : 8;
 
-  Possible values:
-
-  * ``ACS_None`` (in configuration: ``None``)
- Do not align bit fields on consecutive lines.
-
-  * ``ACS_Consecutive`` (in configuration: ``Consecutive``)
- Align bit fields on consecutive lines. This will result in
- formattings like:
-
- .. code-block:: c++
-
-   int  : 1;
-   int b: 12;
-   int ccc  : 8;
-
-   int d : 2;
-   /* A comment. */
-   int ee : 3;
-
-  * ``ACS_AcrossEmptyLines`` (in configuration: ``AcrossEmptyLines``)
- Same as ACS_Consecutive, but also spans over empty lines, e.g.
-
- .. code-block:: c++
-
-   int  : 1;
-   int b: 12;
-   int ccc  : 8;
-
-   int d: 2;
-   /* A comment. */
-   int ee : 3;
-
-  * ``ACS_AcrossComments`` (in configuration: ``AcrossComments``)
- Same as ACS_Consecutive, but also spans over lines only containing
- comments, e.g.
-
- .. code-block:: c++
-
-   int  : 1;
-   int b: 12;
-   int ccc  : 8;
-
-   int d  : 2;
-   /* A comment. */
-   int ee : 3;
-
-  * ``ACS_AcrossEmptyLinesAndComments``
-  (in configuration: ``AcrossEmptyLinesAndComment

[clang] 2563147 - [clang-format] Add the possibility to align assignments spanning empty lines or comments

2021-01-25 Thread Marek Kurdej via cfe-commits

Author: Lukas Barth
Date: 2021-01-25T09:41:50+01:00
New Revision: 256314711f3fa724bff1bb2d8b93c5252265b5c7

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

LOG: [clang-format] Add the possibility to align assignments spanning empty 
lines or comments

Currently, empty lines and comments break alignment of assignments on 
consecutive
lines. This makes the AlignConsecutiveAssignments option an enum that allows 
controlling
whether empty lines or empty lines and comments should be ignored when aligning
assignments.

Reviewed By: MyDeveloperDay, HazardyKnusperkeks, tinloaf

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

Added: 


Modified: 
clang/docs/ClangFormatStyleOptions.rst
clang/docs/ReleaseNotes.rst
clang/docs/tools/dump_format_style.py
clang/include/clang/Format/Format.h
clang/lib/Format/Format.cpp
clang/lib/Format/WhitespaceManager.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 27dcee83a538..6877cac28278 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -195,23 +195,84 @@ the configuration (without a prefix: ``Auto``).
 
 
 
-**AlignConsecutiveAssignments** (``bool``)
-  If ``true``, aligns consecutive assignments.
+**AlignConsecutiveAssignments** (``AlignConsecutiveStyle``)
+  Style of aligning consecutive assignments.
 
-  This will align the assignment operators of consecutive lines. This
-  will result in formattings like
+  ``Consecutive`` will result in formattings like:
 
   .. code-block:: c++
 
-int  = 12;
-int b= 23;
-int ccc  = 23;
+int a= 1;
+int somelongname = 2;
+double c = 3;
 
-**AlignConsecutiveBitFields** (``bool``)
-  If ``true``, aligns consecutive bitfield members.
+  Possible values:
+
+  * ``ACS_None`` (in configuration: ``None``)
+ Do not align assignments on consecutive lines.
+
+  * ``ACS_Consecutive`` (in configuration: ``Consecutive``)
+ Align assignments on consecutive lines. This will result in
+ formattings like:
+
+ .. code-block:: c++
+
+   int a= 1;
+   int somelongname = 2;
+   double c = 3;
+
+   int d = 3;
+   /* A comment. */
+   double e = 4;
+
+  * ``ACS_AcrossEmptyLines`` (in configuration: ``AcrossEmptyLines``)
+ Same as ACS_Consecutive, but also spans over empty lines, e.g.
+
+ .. code-block:: c++
+
+   int a= 1;
+   int somelongname = 2;
+   double c = 3;
+
+   int d= 3;
+   /* A comment. */
+   double e = 4;
+
+  * ``ACS_AcrossComments`` (in configuration: ``AcrossComments``)
+ Same as ACS_Consecutive, but also spans over lines only containing
+ comments, e.g.
+
+ .. code-block:: c++
+
+   int a= 1;
+   int somelongname = 2;
+   double c = 3;
+
+   int d= 3;
+   /* A comment. */
+   double e = 4;
+
+  * ``ACS_AcrossEmptyLinesAndComments``
+(in configuration: ``AcrossEmptyLinesAndComments``)
+
+ Same as ACS_Consecutive, but also spans over lines only containing
+ comments and empty lines, e.g.
+
+ .. code-block:: c++
+
+   int a= 1;
+   int somelongname = 2;
+   double c = 3;
+
+   int d= 3;
+   /* A comment. */
+   double e = 4;
+
+**AlignConsecutiveBitFields** (``AlignConsecutiveStyle``)
+  Style of aligning consecutive bit field.
 
-  This will align the bitfield separators of consecutive lines. This
-  will result in formattings like
+  ``Consecutive`` will align the bitfield separators of consecutive lines.
+  This will result in formattings like:
 
   .. code-block:: c++
 
@@ -219,23 +280,146 @@ the configuration (without a prefix: ``Auto``).
 int b: 12;
 int ccc  : 8;
 
-**AlignConsecutiveDeclarations** (``bool``)
-  If ``true``, aligns consecutive declarations.
+  Possible values:
+
+  * ``ACS_None`` (in configuration: ``None``)
+ Do not align bit fields on consecutive lines.
+
+  * ``ACS_Consecutive`` (in configuration: ``Consecutive``)
+ Align bit fields on consecutive lines. This will result in
+ formattings like:
+
+ .. code-block:: c++
+
+   int  : 1;
+   int b: 12;
+   int ccc  : 8;
+
+   int d : 2;
+   /* A comment. */
+   int ee : 3;
+
+  * ``ACS_AcrossEmptyLines`` (in configuration: ``AcrossEmptyLines``)
+ Same as ACS_Consecutive, but also spans over empty lines, e.g.
+
+ .. code-block:: c++
+
+   int  : 1;
+   int b: 12;
+   int ccc  : 8;
+
+   int d: 2;
+   /* A comment. */
+   int ee : 3;
+
+  * ``ACS_Acros

[clang] 33a63a3 - [clang-format] [docs] Fix RST indentation.

2021-01-25 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2021-01-25T11:00:46+01:00
New Revision: 33a63a36d3cb0a59ef80054a02babe7a28a9842a

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

LOG: [clang-format] [docs] Fix RST indentation.

Added: 


Modified: 
clang/docs/ClangFormatStyleOptions.rst
clang/include/clang/Format/Format.h

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 6877cac28278..3141dd5510fc 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -327,7 +327,7 @@ the configuration (without a prefix: ``Auto``).
int ee : 3;
 
   * ``ACS_AcrossEmptyLinesAndComments``
-  (in configuration: ``AcrossEmptyLinesAndComments``)
+(in configuration: ``AcrossEmptyLinesAndComments``)
 
  Same as ACS_Consecutive, but also spans over lines only containing
  comments and empty lines, e.g.
@@ -401,7 +401,7 @@ the configuration (without a prefix: ``Auto``).
bool c = false;
 
   * ``ACS_AcrossEmptyLinesAndComments``
-  (in configuration: ``AcrossEmptyLinesAndComments``)
+(in configuration: ``AcrossEmptyLinesAndComments``)
 
  Same as ACS_Consecutive, but also spans over lines only containing
  comments and empty lines, e.g.
@@ -476,7 +476,7 @@ the configuration (without a prefix: ``Auto``).
#define bar(y, z) (y + z)
 
   * ``ACS_AcrossEmptyLinesAndComments``
-  (in configuration: ``AcrossEmptyLinesAndComments``)
+(in configuration: ``AcrossEmptyLinesAndComments``)
 
  Same as ACS_Consecutive, but also spans over lines only containing
  comments and empty lines, e.g.

diff  --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index a95689097b00..fcc38e25542f 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -153,7 +153,7 @@ struct FormatStyle {
   ///\endcode
   ///
   /// * ``ACS_AcrossEmptyLinesAndComments``
-  /// (in configuration: ``AcrossEmptyLinesAndComments``)
+  ///   (in configuration: ``AcrossEmptyLinesAndComments``)
   ///
   ///Same as ACS_Consecutive, but also spans over lines only containing
   ///comments and empty lines, e.g.
@@ -290,7 +290,7 @@ struct FormatStyle {
   ///\endcode
   ///
   /// * ``ACS_AcrossEmptyLinesAndComments``
-  /// (in configuration: ``AcrossEmptyLinesAndComments``)
+  ///   (in configuration: ``AcrossEmptyLinesAndComments``)
   ///
   ///Same as ACS_Consecutive, but also spans over lines only containing
   ///comments and empty lines, e.g.
@@ -359,7 +359,7 @@ struct FormatStyle {
   ///\endcode
   ///
   /// * ``ACS_AcrossEmptyLinesAndComments``
-  /// (in configuration: ``AcrossEmptyLinesAndComments``)
+  ///   (in configuration: ``AcrossEmptyLinesAndComments``)
   ///
   ///Same as ACS_Consecutive, but also spans over lines only containing
   ///comments and empty lines, e.g.



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


[clang] 3395a33 - [clang-format] add case aware include sorting

2021-01-25 Thread Marek Kurdej via cfe-commits

Author: Lukas Barth
Date: 2021-01-25T18:53:22+01:00
New Revision: 3395a336b02538d0bb768ccfae11c9b6151b102e

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

LOG: [clang-format] add case aware include sorting

* Adds an option to [clang-format] which sorts
  headers in an alphabetical manner using case
  only for tie-breakers. The options is off by
  default in favor of the current ASCIIbetical
  sorting style.

Reviewed By: curdeius, HazardyKnusperkeks

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

Added: 


Modified: 
clang/docs/ClangFormatStyleOptions.rst
clang/include/clang/Tooling/Inclusions/IncludeStyle.h
clang/lib/Format/Format.cpp
clang/unittests/Format/FormatTest.cpp
clang/unittests/Format/SortIncludesTest.cpp

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 3141dd5510fc..d5ce1b7b2e8e 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -2282,6 +2282,26 @@ the configuration (without a prefix: ``Auto``).
   ``ClassImpl.hpp`` would not have the main include file put on top
   before any other include.
 
+**IncludeSortAlphabetically** (``bool``)
+  Specify if sorting should be done in an alphabetical and
+  case sensitive fashion.
+
+  When ``false``, includes are sorted in an ASCIIbetical
+  fashion.
+  When ``true``, includes are sorted in an alphabetical
+  fashion with case used as a tie-breaker.
+
+  .. code-block:: c++
+
+ false:   true:
+ #include "A/B.h"   vs.   #include "A/B.h"
+ #include "A/b.h" #include "A/b.h"
+ #include "B/A.h" #include "a/b.h"
+ #include "B/a.h" #include "B/A.h"
+ #include "a/b.h" #include "B/a.h"
+
+  This option is off by default.
+
 **IndentCaseBlocks** (``bool``)
   Indent case label blocks one level from the case label.
 

diff  --git a/clang/include/clang/Tooling/Inclusions/IncludeStyle.h 
b/clang/include/clang/Tooling/Inclusions/IncludeStyle.h
index 4caaf4121f15..652a7b61a0a4 100644
--- a/clang/include/clang/Tooling/Inclusions/IncludeStyle.h
+++ b/clang/include/clang/Tooling/Inclusions/IncludeStyle.h
@@ -147,6 +147,26 @@ struct IncludeStyle {
   /// ``ClassImpl.hpp`` would not have the main include file put on top
   /// before any other include.
   std::string IncludeIsMainSourceRegex;
+
+  /// Specify if sorting should be done in an alphabetical and
+  /// case sensitive fashion.
+  ///
+  /// When ``false``, includes are sorted in an ASCIIbetical
+  /// fashion.
+  /// When ``true``, includes are sorted in an alphabetical
+  /// fashion with case used as a tie-breaker.
+  ///
+  /// \code
+  ///   false:   true:
+  ///   #include "A/B.h"   vs.   #include "A/B.h"
+  ///   #include "A/b.h" #include "A/b.h"
+  ///   #include "B/A.h" #include "a/b.h"
+  ///   #include "B/a.h" #include "B/A.h"
+  ///   #include "a/b.h" #include "B/a.h"
+  /// \endcode
+  ///
+  /// This option is off by default.
+  bool IncludeSortAlphabetically;
 };
 
 } // namespace tooling

diff  --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index cd1c6e4f6023..0986ef845a4e 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -571,6 +571,8 @@ template <> struct MappingTraits {
 IO.mapOptional("IncludeIsMainRegex", 
Style.IncludeStyle.IncludeIsMainRegex);
 IO.mapOptional("IncludeIsMainSourceRegex",
Style.IncludeStyle.IncludeIsMainSourceRegex);
+IO.mapOptional("IncludeSortAlphabetically",
+   Style.IncludeStyle.IncludeSortAlphabetically);
 IO.mapOptional("IndentCaseLabels", Style.IndentCaseLabels);
 IO.mapOptional("IndentCaseBlocks", Style.IndentCaseBlocks);
 IO.mapOptional("IndentGotoLabels", Style.IndentGotoLabels);
@@ -940,6 +942,7 @@ FormatStyle getLLVMStyle(FormatStyle::LanguageKind 
Language) {
   {".*", 1, 0, false}};
   LLVMStyle.IncludeStyle.IncludeIsMainRegex = "(Test)?$";
   LLVMStyle.IncludeStyle.IncludeBlocks = tooling::IncludeStyle::IBS_Preserve;
+  LLVMStyle.IncludeStyle.IncludeSortAlphabetically = false;
   LLVMStyle.IndentCaseLabels = false;
   LLVMStyle.IndentCaseBlocks = false;
   LLVMStyle.IndentGotoLabels = true;
@@ -2194,10 +2197,23 @@ static void sortCppIncludes(const FormatStyle &Style,
   for (unsigned i = 0, e = Includes.size(); i != e; ++i) {
 Indices.push_back(i);
   }
-  llvm::stable_sort(Indices, [&](unsigned LHSI, unsigned RHSI) {
-return std::tie(Includes[LHSI].Priority, Includes[

[clang] a8105b3 - [clang-format] Add case aware include sorting.

2021-02-02 Thread Marek Kurdej via cfe-commits

Author: Kent Sommer
Date: 2021-02-02T15:12:27+01:00
New Revision: a8105b3766e4195ca2390cd0714e07406bc8a4a5

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

LOG: [clang-format] Add case aware include sorting.

Adds an option to [clang-format] which sorts headers in an alphabetical manner 
using case only for tie-breakers. The options is off by default in favor of the 
current ASCIIbetical sorting style.

Reviewed By: MyDeveloperDay, curdeius, HazardyKnusperkeks

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

Added: 


Modified: 
clang/docs/ClangFormatStyleOptions.rst
clang/docs/ReleaseNotes.rst
clang/include/clang/Format/Format.h
clang/lib/Format/Format.cpp
clang/tools/clang-format/ClangFormat.cpp
clang/unittests/Format/FormatTest.cpp
clang/unittests/Format/SortImportsTestJava.cpp
clang/unittests/Format/SortIncludesTest.cpp

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index a28efa5dad04..d55c0d59b36a 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -3004,14 +3004,43 @@ the configuration (without a prefix: ``Auto``).
  /* second veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongComment with 
plenty of
   * information */
 
-**SortIncludes** (``bool``)
-  If ``true``, clang-format will sort ``#includes``.
+**SortIncludes** (``SortIncludesOptions``)
+  Controls if and how clang-format will sort ``#includes``.
 
-  .. code-block:: c++
+  Possible Values:
 
- false: true:
- #include "b.h" vs. #include "a.h"
- #include "a.h" #include "b.h"
+  * ``SI_Never`` (in configuration ``Never``)
+Includes are never sorted.
+
+.. code-block:: c++
+
+  #include "B/A.h"
+  #include "A/B.h"
+  #include "a/b.h"
+  #include "A/b.h"
+  #include "B/a.h"
+
+  * ``SI_CaseInsensitive`` (in configuration ``CaseInsensitive``)
+Includes are sorted in an ASCIIbetical or case insensitive fashion.
+
+.. code-block:: c++
+
+  #include "A/B.h"
+  #include "A/b.h"
+  #include "B/A.h"
+  #include "B/a.h"
+  #include "a/b.h"
+
+  * ``SI_CaseSensitive`` (in configuration ``CaseSensitive``)
+Includes are sorted in an alphabetical or case sensitive fashion.
+
+.. code-block:: c++
+
+  #include "A/B.h"
+  #include "A/b.h"
+  #include "a/b.h"
+  #include "B/A.h"
+  #include "B/a.h"
 
 **SortJavaStaticImport** (``SortJavaStaticImportOptions``)
   When sorting Java imports, by default static imports are placed before

diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 6c5c993f98b1..d1a5156f0d00 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -159,6 +159,35 @@ clang-format
 - Option ``SpacesInLineCommentPrefix`` has been added to control the
   number of spaces in a line comments prefix.
 
+- Option ``SortIncludes`` has been updated from a ``bool`` to an
+  ``enum`` with backwards compatibility. In addition to the previous
+  ``true``/``false`` states (now ``CaseInsensitive``/``Never``), a third
+  state has been added (``CaseSensitive``) which causes an alphabetical sort
+  with case used as a tie-breaker.
+
+  .. code-block:: c++
+
+// Never (previously false)
+#include "B/A.h"
+#include "A/B.h"
+#include "a/b.h"
+#include "A/b.h"
+#include "B/a.h"
+
+// CaseInsensitive (previously true)
+#include "A/B.h"
+#include "A/b.h"
+#include "B/A.h"
+#include "B/a.h"
+#include "a/b.h"
+
+// CaseSensitive
+#include "A/B.h"
+#include "A/b.h"
+#include "a/b.h"
+#include "B/A.h"
+#include "B/a.h"
+
 libclang
 
 

diff  --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 269707fedaac..7cedbfb80610 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -2613,13 +2613,44 @@ struct FormatStyle {
   bool ReflowComments;
   // clang-format on
 
-  /// If ``true``, clang-format will sort ``#includes``.
-  /// \code
-  ///false: true:
-  ///#include "b.h" vs. #include "a.h"
-  ///#include "a.h" #include "b.h"
-  /// \endcode
-  bool SortIncludes;
+  /// Include sorting options.
+  enum SortIncludesOptions : unsigned char {
+/// Includes are never sorted.
+/// \code
+///#include "B/A.h"
+///#include "A/B.h"
+///#include "a/b.h"
+///#include "A/b.h"
+///#include "B/a.h"
+/// \endcode
+SI_Never,
+/// Includes are sorted in an ASCIIbetical or case insensitive fashion

[clang] 2c60cfc - [format] [docs] Fix typos and clarify QualifierAlignment/QualifierOrder documentation.

2021-09-30 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2021-09-30T09:42:34+02:00
New Revision: 2c60cfc05f6fb32f128688c4cfffb09a978d539f

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

LOG: [format] [docs] Fix typos and clarify QualifierAlignment/QualifierOrder 
documentation.

Added: 


Modified: 
clang/docs/ClangFormatStyleOptions.rst
clang/include/clang/Format/Format.h
clang/lib/Format/QualifierAlignmentFixer.cpp
clang/lib/Format/TokenAnnotator.cpp

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 0bdb73a74e3b3..7e4d1582d866f 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -3234,7 +3234,7 @@ the configuration (without a prefix: ``Auto``).
 
 
 **QualifierAlignment** (``QualifierAlignmentStyle``) 
:versionbadge:`clang-format 14`
-  Different ways to arrange const/volatile qualifiers.
+  Different ways to arrange specifiers and qualifiers (e.g. const/volatile).
 
   .. warning:: 
 
@@ -3243,8 +3243,8 @@ the configuration (without a prefix: ``Auto``).
   Possible values:
 
   * ``QAS_Leave`` (in configuration: ``Leave``)
-Don't change specifiers/qualifier to either Left or Right alignment
-(default)
+Don't change specifiers/qualifiers to either Left or Right alignment
+(default).
 
 .. code-block:: c++
 
@@ -3252,7 +3252,7 @@ the configuration (without a prefix: ``Auto``).
const int *a;
 
   * ``QAS_Left`` (in configuration: ``Left``)
-Change specifiers/qualifiers to be Left aligned.
+Change specifiers/qualifiers to be left-aligned.
 
 .. code-block:: c++
 
@@ -3260,7 +3260,7 @@ the configuration (without a prefix: ``Auto``).
const int *a;
 
   * ``QAS_Right`` (in configuration: ``Right``)
-Change specifiers/qualifiers to be Right aligned.
+Change specifiers/qualifiers to be right-aligned.
 
 .. code-block:: c++
 
@@ -3268,12 +3268,12 @@ the configuration (without a prefix: ``Auto``).
int const *a;
 
   * ``QAS_Custom`` (in configuration: ``Custom``)
-Change specifiers/qualifiers to be aligned based on QualfierOrder.
+Change specifiers/qualifiers to be aligned based on ``QualifierOrder``.
 With:
 
 .. code-block:: yaml
 
-  QualifierOrder: ['inline', 'static' , '', 'const']
+  QualifierOrder: ['inline', 'static' , 'type', 'const']
 
 
 .. code-block:: c++
@@ -3285,8 +3285,8 @@ the configuration (without a prefix: ``Auto``).
 
 
 **QualifierOrder** (``List of Strings``) :versionbadge:`clang-format 14`
-  The Order in which the qualifiers appear.
-  Order is a an array can contain any of the following
+  The order in which the qualifiers appear.
+  Order is an array that can contain any of the following:
 
 * const
 * inline
@@ -3297,8 +3297,8 @@ the configuration (without a prefix: ``Auto``).
 * type
 
   Note: it MUST contain 'type'.
-  Items to the left of type will be aligned in the order supplied.
-  Items to the right of type will be aligned  in the order supplied.
+  Items to the left of 'type' will be placed to the left of the type and 
aligned in the order supplied.
+  Items to the right of 'type' will be placed to the right of the type and 
aligned in the order supplied.
 
 
   .. code-block:: yaml

diff  --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index f5e7b5f5c149b..a6fd44693a033 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -1861,31 +1861,31 @@ struct FormatStyle {
   /// \version 3.7
   std::string CommentPragmas;
 
-  /// Different const/volatile qualifier alignment styles.
+  /// Different specifiers and qualifiers alignment styles.
   enum QualifierAlignmentStyle {
-/// Don't change specifiers/qualifier to either Left or Right alignment
-/// (default)
+/// Don't change specifiers/qualifiers to either Left or Right alignment
+/// (default).
 /// \code
 ///int const a;
 ///const int *a;
 /// \endcode
 QAS_Leave,
-/// Change specifiers/qualifiers to be Left aligned.
+/// Change specifiers/qualifiers to be left-aligned.
 /// \code
 ///const int a;
 ///const int *a;
 /// \endcode
 QAS_Left,
-/// Change specifiers/qualifiers to be Right aligned.
+/// Change specifiers/qualifiers to be right-aligned.
 /// \code
 ///int const a;
 ///int const *a;
 /// \endcode
 QAS_Right,
-/// Change specifiers/qualifiers to be aligned based on QualfierOrder.
+/// Change specifiers/qualifiers to be aligned based on ``QualifierOrder``.
 /// With:
 /// \code{.yaml}
-///   QualifierOrder: ['inline', 'static' , '', 'const']
+///   QualifierOrder: ['inline', 'st

[clang] 21c18d5 - [Format] Fix incorrect pointer detection

2021-06-04 Thread Marek Kurdej via cfe-commits

Author: Yilong Guo
Date: 2021-06-04T09:39:23+02:00
New Revision: 21c18d5a04316891110cecc2bf37ce51533decba

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

LOG: [Format] Fix incorrect pointer detection

https://llvm.org/PR50429

Before:
void f() { f(float(1), a *a); }

After:
void f() { f(float(1), a * a); }

Signed-off-by: Yilong Guo 

Reviewed By: HazardyKnusperkeks, curdeius

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 4bd9311ebadd4..d08c991daf43f 100755
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -399,7 +399,7 @@ class AnnotatingParser {
 HasMultipleParametersOnALine = true;
   if ((CurrentToken->Previous->isOneOf(tok::kw_const, tok::kw_auto) ||
CurrentToken->Previous->isSimpleTypeSpecifier()) &&
-  !CurrentToken->is(tok::l_brace))
+  !CurrentToken->isOneOf(tok::l_brace, tok::l_paren))
 Contexts.back().IsExpression = false;
   if (CurrentToken->isOneOf(tok::semi, tok::colon)) {
 MightBeObjCForRangeLoop = false;

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index a2583aecf5a9f..5ea4fcc9ffe36 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -8706,6 +8706,7 @@ TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
 
   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
   verifyFormat("void f() { f(float{1}, a * a); }");
+  verifyFormat("void f() { f(float(1), a * a); }");
   // FIXME: Is there a way to make this work?
   // verifyIndependentOfContext("MACRO(A *a);");
   verifyFormat("MACRO(A &B);");



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


[clang] 2a42c75 - [clang-format] [PR19056] Add support for access modifiers indentation

2021-02-26 Thread Marek Kurdej via cfe-commits

Author: Jakub Budiský
Date: 2021-02-26T09:17:07+01:00
New Revision: 2a42c759ae7bb09dd448d188138f310d014fcab6

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

LOG: [clang-format] [PR19056] Add support for access modifiers indentation

Adds support for coding styles that make a separate indentation level for 
access modifiers, such as Code::Blocks or QtCreator.

The new option, `IndentAccessModifiers`, if enabled, forces the content inside 
classes, structs and unions (“records”) to be indented twice while removing a 
level for access modifiers. The value of `AccessModifierOffset` is disregarded 
in this case, aiming towards an ease of use.

==
The PR (https://bugs.llvm.org/show_bug.cgi?id=19056) had an implementation 
attempt by @MyDeveloperDay already (https://reviews.llvm.org/D60225) but I've 
decided to start from scratch. They differ in functionality, chosen approaches, 
and even the option name. The code tries to re-use the existing functionality 
to achieve this behavior, limiting possibility of breaking something else.

Reviewed By: MyDeveloperDay, curdeius, HazardyKnusperkeks

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

Added: 


Modified: 
clang/docs/ClangFormatStyleOptions.rst
clang/docs/ReleaseNotes.rst
clang/include/clang/Format/Format.h
clang/lib/Format/Format.cpp
clang/lib/Format/UnwrappedLineFormatter.cpp
clang/lib/Format/UnwrappedLineParser.cpp
clang/lib/Format/UnwrappedLineParser.h
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 7ae8ea913099..1dbf11987cd8 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -2360,6 +2360,33 @@ the configuration (without a prefix: ``Auto``).
   ``ClassImpl.hpp`` would not have the main include file put on top
   before any other include.
 
+**IndentAccessModifiers** (``bool``)
+  Specify whether access modifiers should have their own indentation level.
+
+  When ``false``, access modifiers are indented (or outdented) relative to
+  the record members, respecting the ``AccessModifierOffset``. Record
+  members are indented one level below the record.
+  When ``true``, access modifiers get their own indentation level. As a
+  consequence, record members are indented 2 levels below the record,
+  regardless of the access modifier presence. Value of the
+  ``AccessModifierOffset`` is ignored.
+
+  .. code-block:: c++
+
+ false: true:
+ class C {  vs. class C {
+   class D {class D {
+ void bar();void bar();
+   protected: protected:
+ D();   D();
+   };   };
+ public:  public:
+   C(); C();
+ }; };
+ void foo() {   void foo() {
+   return 1;  return 1;
+ }  }
+
 **IndentCaseBlocks** (``bool``)
   Indent case label blocks one level from the case label.
 

diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 26b380407c0b..6a0ebd9ab3ee 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -196,6 +196,9 @@ clang-format
 - ``BasedOnStyle: InheritParentConfig`` allows to use the ``.clang-format`` of
   the parent directories to overwrite only parts of it.
 
+- Option ``IndentAccessModifiers`` has been added to be able to give access
+  modifiers their own indentation level inside records.
+
 libclang
 
 

diff  --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 1a669ebf07f5..d60c56058a85 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -2047,6 +2047,32 @@ struct FormatStyle {
 
   tooling::IncludeStyle IncludeStyle;
 
+  /// Specify whether access modifiers should have their own indentation level.
+  ///
+  /// When ``false``, access modifiers are indented (or outdented) relative to
+  /// the record members, respecting the ``AccessModifierOffset``. Record
+  /// members are indented one level below the record.
+  /// When ``true``, access modifiers get their own indentation level. As a
+  /// consequence, record members are always indented 2 levels below the 
record,
+  /// regardless of the access modifier presence. Value of the
+  /// ``AccessModifierOffset`` is ignored.
+  /// \code
+  ///false: true:

[clang] d4d28f2 - [clang-format] Fix QualifierAlignment with global namespace qualified types.

2022-05-26 Thread Marek Kurdej via cfe-commits

Author: Marek Kurdej
Date: 2022-05-26T15:02:33+02:00
New Revision: d4d28f2ace764a0420a33462628b43a1c71fc3dc

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

LOG: [clang-format] Fix QualifierAlignment with global namespace qualified 
types.

Fixes https://github.com/llvm/llvm-project/issues/55610.

Reviewed By: MyDeveloperDay

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

Added: 


Modified: 
clang/lib/Format/QualifierAlignmentFixer.cpp
clang/unittests/Format/QualifierFixerTest.cpp

Removed: 




diff  --git a/clang/lib/Format/QualifierAlignmentFixer.cpp 
b/clang/lib/Format/QualifierAlignmentFixer.cpp
index dd12298a57ff..61f17cae383e 100644
--- a/clang/lib/Format/QualifierAlignmentFixer.cpp
+++ b/clang/lib/Format/QualifierAlignmentFixer.cpp
@@ -216,6 +216,29 @@ const FormatToken 
*LeftRightQualifierAlignmentFixer::analyzeRight(
   if (LeftRightQualifierAlignmentFixer::isPossibleMacro(Tok->Next))
 return Tok;
 
+  auto AnalyzeTemplate =
+  [&](const FormatToken *Tok,
+  const FormatToken *StartTemplate) -> const FormatToken * {
+// Read from the TemplateOpener to TemplateCloser.
+FormatToken *EndTemplate = StartTemplate->MatchingParen;
+if (EndTemplate) {
+  // Move to the end of any template class members e.g.
+  // `Foo::iterator`.
+  if (EndTemplate->startsSequence(TT_TemplateCloser, tok::coloncolon,
+  tok::identifier)) {
+EndTemplate = EndTemplate->Next->Next;
+  }
+}
+if (EndTemplate && EndTemplate->Next &&
+!EndTemplate->Next->isOneOf(tok::equal, tok::l_paren)) {
+  insertQualifierAfter(SourceMgr, Fixes, EndTemplate, Qualifier);
+  // Remove the qualifier.
+  removeToken(SourceMgr, Fixes, Tok);
+  return Tok;
+}
+return nullptr;
+  };
+
   FormatToken *Qual = Tok->Next;
   FormatToken *LastQual = Qual;
   while (Qual && isQualifierOrType(Qual, ConfiguredQualifierTokens)) {
@@ -233,27 +256,24 @@ const FormatToken 
*LeftRightQualifierAlignmentFixer::analyzeRight(
 return Tok;
   } else if (Tok->startsSequence(QualifierType, tok::identifier,
  TT_TemplateOpener)) {
-// Read from the TemplateOpener to
-// TemplateCloser as in const ArrayRef a; const ArrayRef &a;
-FormatToken *EndTemplate = Tok->Next->Next->MatchingParen;
-if (EndTemplate) {
-  // Move to the end of any template class members e.g.
-  // `Foo::iterator`.
-  if (EndTemplate->startsSequence(TT_TemplateCloser, tok::coloncolon,
-  tok::identifier)) {
-EndTemplate = EndTemplate->Next->Next;
-  }
-}
-if (EndTemplate && EndTemplate->Next &&
-!EndTemplate->Next->isOneOf(tok::equal, tok::l_paren)) {
-  insertQualifierAfter(SourceMgr, Fixes, EndTemplate, Qualifier);
-  // Remove the qualifier.
-  removeToken(SourceMgr, Fixes, Tok);
-  return Tok;
-}
-  } else if (Tok->startsSequence(QualifierType, tok::identifier)) {
+// `const ArrayRef a;`
+// `const ArrayRef &a;`
+const FormatToken *NewTok = AnalyzeTemplate(Tok, Tok->Next->Next);
+if (NewTok)
+  return NewTok;
+  } else if (Tok->startsSequence(QualifierType, tok::coloncolon,
+ tok::identifier, TT_TemplateOpener)) {
+// `const ::ArrayRef a;`
+// `const ::ArrayRef &a;`
+const FormatToken *NewTok = AnalyzeTemplate(Tok, Tok->Next->Next->Next);
+if (NewTok)
+  return NewTok;
+  } else if (Tok->startsSequence(QualifierType, tok::identifier) ||
+ Tok->startsSequence(QualifierType, tok::coloncolon,
+ tok::identifier)) {
 FormatToken *Next = Tok->Next;
 // The case  `const Foo` -> `Foo const`
+// The case  `const ::Foo` -> `::Foo const`
 // The case  `const Foo *` -> `Foo const *`
 // The case  `const Foo &` -> `Foo const &`
 // The case  `const Foo &&` -> `Foo const &&`
@@ -331,7 +351,9 @@ const FormatToken 
*LeftRightQualifierAlignmentFixer::analyzeLeft(
   Tok->Next->Next && Tok->Next->Next->is(QualifierType)) {
 rotateTokens(SourceMgr, Fixes, Tok->Next, Tok->Next->Next, /*Left=*/true);
   }
-  if (Tok->startsSequence(tok::identifier) && Tok->Next) {
+  if ((Tok->startsSequence(tok::coloncolon, tok::identifier) ||
+   Tok->is(tok::identifier)) &&
+  Tok->Next) {
 if (Tok->Previous &&
 Tok->Previous->isOneOf(tok::star, tok::ampamp, tok::amp)) {
   return Tok;

diff  --git a/clang/unittests/Format/QualifierFixerTest.cpp 
b/clang/unittests/Format/QualifierFixerTest.cpp
index fc7e932af440..b01aff53150d 100755
--- a/clang/unittests/Format/QualifierFixerTest.cpp
+++ b/clang/unittests/Format/QualifierFixerTest.cpp
@@ -318,6 +31

[clang] 8f70d16 - [clang-format] Handle attributes in enum declaration.

2022-05-26 Thread Marek Kurdej via cfe-commits

Author: Tyler Chatow
Date: 2022-05-26T15:43:57+02:00
New Revision: 8f70d16c9ab2d7c060f5c92a31a0fc4a82349897

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

LOG: [clang-format] Handle attributes in enum declaration.

Fixes https://github.com/llvm/llvm-project/issues/55457

Ensures that attributes in the enum declaration are interpreted
correctly, for instance:

```
enum class [[nodiscard]] E {
  a,
  b
};
```

Reviewed By: MyDeveloperDay, curdeius

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

Added: 


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

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index a20562dd77a4..0611e9eace47 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -3419,11 +3419,18 @@ bool UnwrappedLineParser::parseEnum() {
 
   while (FormatTok->Tok.getIdentifierInfo() ||
  FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
-tok::greater, tok::comma, tok::question)) {
+tok::greater, tok::comma, tok::question,
+tok::l_square, tok::r_square)) {
 nextToken();
 // We can have macros or attributes in between 'enum' and the enum name.
 if (FormatTok->is(tok::l_paren))
   parseParens();
+if (FormatTok->is(TT_AttributeSquare)) {
+  parseSquare();
+  // Consume the closing TT_AttributeSquare.
+  if (FormatTok->Next && FormatTok->is(TT_AttributeSquare))
+nextToken();
+}
 if (FormatTok->is(tok::identifier)) {
   nextToken();
   // If there are two identifiers in a row, this is likely an elaborate

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 3621ba667818..44ef882fe7db 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -3573,6 +3573,7 @@ TEST_F(FormatTest, FormatsEnum) {
   verifyFormat("enum X E {} d;");
   verifyFormat("enum __attribute__((...)) E {} d;");
   verifyFormat("enum __declspec__((...)) E {} d;");
+  verifyFormat("enum [[nodiscard]] E {} d;");
   verifyFormat("enum {\n"
"  Bar = Foo::value\n"
"};",
@@ -3619,6 +3620,17 @@ TEST_F(FormatTest, FormatsEnum) {
"};",
EightIndent);
 
+  verifyFormat("enum [[nodiscard]] E {\n"
+   "  ONE,\n"
+   "  TWO,\n"
+   "};");
+  verifyFormat("enum [[nodiscard]] E {\n"
+   "  // Comment 1\n"
+   "  ONE,\n"
+   "  // Comment 2\n"
+   "  TWO,\n"
+   "};");
+
   // Not enums.
   verifyFormat("enum X f() {\n"
"  a();\n"
@@ -3666,7 +3678,19 @@ TEST_F(FormatTest, FormatsEnumStruct) {
   verifyFormat("enum struct X E {} d;");
   verifyFormat("enum struct __attribute__((...)) E {} d;");
   verifyFormat("enum struct __declspec__((...)) E {} d;");
+  verifyFormat("enum struct [[nodiscard]] E {} d;");
   verifyFormat("enum struct X f() {\n  a();\n  return 42;\n}");
+
+  verifyFormat("enum struct [[nodiscard]] E {\n"
+   "  ONE,\n"
+   "  TWO,\n"
+   "};");
+  verifyFormat("enum struct [[nodiscard]] E {\n"
+   "  // Comment 1\n"
+   "  ONE,\n"
+   "  // Comment 2\n"
+   "  TWO,\n"
+   "};");
 }
 
 TEST_F(FormatTest, FormatsEnumClass) {
@@ -3683,7 +3707,19 @@ TEST_F(FormatTest, FormatsEnumClass) {
   verifyFormat("enum class X E {} d;");
   verifyFormat("enum class __attribute__((...)) E {} d;");
   verifyFormat("enum class __declspec__((...)) E {} d;");
+  verifyFormat("enum class [[nodiscard]] E {} d;");
   verifyFormat("enum class X f() {\n  a();\n  return 42;\n}");
+
+  verifyFormat("enum class [[nodiscard]] E {\n"
+   "  ONE,\n"
+   "  TWO,\n"
+   "};");
+  verifyFormat("enum class [[nodiscard]] E {\n"
+   "  // Comment 1\n"
+   "  ONE,\n"
+   "  // Comment 2\n"
+   "  TWO,\n"
+   "};");
 }
 
 TEST_F(FormatTest, FormatsEnumTypes) {



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


Re: [PATCH] D24192: [clang-refactor] introducing clang-refactor

2016-09-07 Thread Marek Kurdej via cfe-commits
curdeius added a subscriber: curdeius.
curdeius added a comment.

For the moment, just a few nitty-gritty comments inline.
What I miss here is (as already pointed by someone) an example on how to write 
a new module, register it etc.



Comment at: clang-refactor/driver/Driver.cpp:41
@@ +40,3 @@
+Command = argv[1];
+std::string Invocation = std::string(argv[0]) + " " + argv[1];
+argv[1] = Invocation.c_str();

Simpler:

```
std::string Invocation = argv[0] + (" " + Command);
```


Comment at: clang-refactor/driver/ModuleManager.cpp:22-24
@@ +21,5 @@
+int ModuleManager::Dispatch(StringRef Command, int argc, const char **argv) {
+  if (CommandToModuleID.find(Command) != CommandToModuleID.end()) {
+return RegisteredModules[CommandToModuleID[Command]]->run(argc, argv);
+  }
+  return 1;

Using `find` and then `operator[]` makes the search twice. IMO, it would be 
better to avoid that by:

```
  auto it = CommandToModuleID.find(Command);
  if (it != CommandToModuleID.end()) {
return RegisteredModules[*it]->run(argc, argv);
  }
```


Comment at: clang-refactor/driver/ModuleManager.h:13-19
@@ +12,9 @@
+
+#include "llvm/ADT/StringRef.h"
+
+#include 
+#include 
+#include 
+
+#include "core/RefactoringModule.h"
+

clang-format includes (and make it a single block)?


Comment at: clang-refactor/driver/ModuleManager.h:21
@@ +20,3 @@
+
+using namespace llvm;
+

`using namespace` in header?!


Comment at: clang-refactor/modules/core/RefactoringModule.h:36
@@ +35,3 @@
+  //
+  // 1. Extract infromation needed for the refactoring upon tool invocation.
+  //

s/infromation/information


Comment at: clang-refactor/modules/core/RefactoringModule.h:56
@@ +55,3 @@
+  // 2. Check whether renaming will introduce any name conflicts. If it won't
+  // find each occurance of the symbol in translation unit using USR and store
+  // replacements.

s/occurance/occurrence


Comment at: clang-refactor/modules/core/RefactoringModule.h:72
@@ +71,3 @@
+  // code will no longer compile. If it won't find function calls, add needed
+  // temprorary variables and replace the call with function body.
+  //

s/temprorary/temporary


Comment at: clang-refactor/modules/core/RefactoringModule.h:112
@@ +111,3 @@
+
+  // Routine for regiestering common modules options.
+  void registerCommonOptions(llvm::cl::OptionCategory &Category) {

s/regiestering/registering


https://reviews.llvm.org/D24192



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


Re: [PATCH] D24192: [clang-refactor] introducing clang-refactor

2016-09-08 Thread Marek Kurdej via cfe-commits
curdeius added inline comments.


Comment at: clang-refactor/driver/ModuleManager.h:14-20
@@ +13,9 @@
+#include "clang/Basic/LLVM.h"
+#include "llvm/ADT/StringRef.h"
+
+#include 
+#include 
+#include 
+
+#include "core/RefactoringModule.h"
+

I thought that idea behind sorting includes using clang-format is to avoid 
handling groups and order manually.
I don't think that there is any policy prohibiting separating includes into 
groups, but AFAIK, there is one that says that STL includes should be the last 
(you should include in order from the most specific to the most generic, i.e. 
subproject, clang, llvm, STL).


https://reviews.llvm.org/D24192



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


[clang-tools-extra] r298621 - [clang-tidy] Fix treating non-space whitespaces in checks list.

2017-03-23 Thread Marek Kurdej via cfe-commits
Author: mkurdej
Date: Thu Mar 23 11:32:06 2017
New Revision: 298621

URL: http://llvm.org/viewvc/llvm-project?rev=298621&view=rev
Log:
[clang-tidy] Fix treating non-space whitespaces in checks list.

Summary:
This furtherly improves r295303: [clang-tidy] Ignore spaces between globs in 
the Checks option.
Trims all whitespaces and not only spaces and correctly computes the offset of 
the checks list (taking the size before trimming).

Reviewers: alexfh

Reviewed By: alexfh

Subscribers: cfe-commits, JDevlieghere

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

Modified:
clang-tools-extra/trunk/clang-tidy/ClangTidyDiagnosticConsumer.cpp

clang-tools-extra/trunk/unittests/clang-tidy/ClangTidyDiagnosticConsumerTest.cpp

Modified: clang-tools-extra/trunk/clang-tidy/ClangTidyDiagnosticConsumer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/ClangTidyDiagnosticConsumer.cpp?rev=298621&r1=298620&r2=298621&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/ClangTidyDiagnosticConsumer.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/ClangTidyDiagnosticConsumer.cpp Thu Mar 
23 11:32:06 2017
@@ -1,618 +1,619 @@
-//===--- tools/extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp --=== 
//
-//
-// The LLVM Compiler Infrastructure
-//
-// This file is distributed under the University of Illinois Open Source
-// License. See LICENSE.TXT for details.
-//
-//===--===//
-///
-///  \file This file implements ClangTidyDiagnosticConsumer, ClangTidyContext
-///  and ClangTidyError classes.
-///
-///  This tool uses the Clang Tooling infrastructure, see
-///http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html
-///  for details on setting it up with LLVM source tree.
-///
-//===--===//
-
-#include "ClangTidyDiagnosticConsumer.h"
-#include "ClangTidyOptions.h"
-#include "clang/AST/ASTDiagnostic.h"
-#include "clang/Basic/DiagnosticOptions.h"
-#include "clang/Frontend/DiagnosticRenderer.h"
-#include "llvm/ADT/SmallString.h"
-#include 
-#include 
-using namespace clang;
-using namespace tidy;
-
-namespace {
-class ClangTidyDiagnosticRenderer : public DiagnosticRenderer {
-public:
-  ClangTidyDiagnosticRenderer(const LangOptions &LangOpts,
-  DiagnosticOptions *DiagOpts,
-  ClangTidyError &Error)
-  : DiagnosticRenderer(LangOpts, DiagOpts), Error(Error) {}
-
-protected:
-  void emitDiagnosticMessage(SourceLocation Loc, PresumedLoc PLoc,
- DiagnosticsEngine::Level Level, StringRef Message,
- ArrayRef Ranges,
- const SourceManager *SM,
- DiagOrStoredDiag Info) override {
-// Remove check name from the message.
-// FIXME: Remove this once there's a better way to pass check names than
-// appending the check name to the message in ClangTidyContext::diag and
-// using getCustomDiagID.
-std::string CheckNameInMessage = " [" + Error.DiagnosticName + "]";
-if (Message.endswith(CheckNameInMessage))
-  Message = Message.substr(0, Message.size() - CheckNameInMessage.size());
-
-auto TidyMessage = Loc.isValid()
-   ? tooling::DiagnosticMessage(Message, *SM, Loc)
-   : tooling::DiagnosticMessage(Message);
-if (Level == DiagnosticsEngine::Note) {
-  Error.Notes.push_back(TidyMessage);
-  return;
-}
-assert(Error.Message.Message.empty() && "Overwriting a diagnostic 
message");
-Error.Message = TidyMessage;
-  }
-
-  void emitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc,
- DiagnosticsEngine::Level Level,
- ArrayRef Ranges,
- const SourceManager &SM) override {}
-
-  void emitCodeContext(SourceLocation Loc, DiagnosticsEngine::Level Level,
-   SmallVectorImpl &Ranges,
-   ArrayRef Hints,
-   const SourceManager &SM) override {
-assert(Loc.isValid());
-for (const auto &FixIt : Hints) {
-  CharSourceRange Range = FixIt.RemoveRange;
-  assert(Range.getBegin().isValid() && Range.getEnd().isValid() &&
- "Invalid range in the fix-it hint.");
-  assert(Range.getBegin().isFileID() && Range.getEnd().isFileID() &&
- "Only file locations supported in fix-it hints.");
-
-  tooling::Replacement Replacement(SM, Range, FixIt.CodeToInsert);
-  llvm::Error Err = Error.Fix[Replacement.getFilePath()].add(Replacement);
-  // FIXME: better error handling (at least, don't let other replacements 
be
-  // applied).
-  if (Err) {
-llvm::errs() << "Fix conflicts with existing fix! "
- <<

[PATCH] D25770: [clang-tidy] Add cert-err09-cpp check alias.

2016-10-19 Thread Marek Kurdej via cfe-commits
curdeius created this revision.
curdeius added reviewers: alexfh, hokein.
curdeius added a subscriber: cfe-commits.

This adds cert-err09-cpp alias for completeness, similar to cert-err61-cpp.


https://reviews.llvm.org/D25770

Files:
  clang-tidy/cert/CERTTidyModule.cpp
  docs/clang-tidy/checks/cert-err09-cpp.rst
  docs/clang-tidy/checks/list.rst
  docs/clang-tidy/checks/misc-throw-by-value-catch-by-reference.rst


Index: docs/clang-tidy/checks/misc-throw-by-value-catch-by-reference.rst
===
--- docs/clang-tidy/checks/misc-throw-by-value-catch-by-reference.rst
+++ docs/clang-tidy/checks/misc-throw-by-value-catch-by-reference.rst
@@ -3,6 +3,7 @@
 misc-throw-by-value-catch-by-reference
 ==
 
+"cert-err09-cpp" redirects here as an alias for this check.
 "cert-err61-cpp" redirects here as an alias for this check.
 
 Finds violations of the rule "Throw by value, catch by reference" presented for
Index: docs/clang-tidy/checks/list.rst
===
--- docs/clang-tidy/checks/list.rst
+++ docs/clang-tidy/checks/list.rst
@@ -10,6 +10,7 @@
cert-dcl54-cpp (redirects to misc-new-delete-overloads) 
cert-dcl59-cpp (redirects to google-build-namespaces) 
cert-env33-c
+   cert-err09-cpp (redirects to misc-throw-by-value-catch-by-reference) 

cert-err34-c
cert-err52-cpp
cert-err58-cpp
Index: docs/clang-tidy/checks/cert-err09-cpp.rst
===
--- /dev/null
+++ docs/clang-tidy/checks/cert-err09-cpp.rst
@@ -0,0 +1,10 @@
+.. title:: clang-tidy - cert-err09-cpp
+.. meta::
+   :http-equiv=refresh: 5;URL=misc-throw-by-value-catch-by-reference.html
+
+cert-err09-cpp
+==
+
+The cert-err09-cpp check is an alias, please see
+`misc-throw-by-value-catch-by-reference 
`_
+for more information.
Index: clang-tidy/cert/CERTTidyModule.cpp
===
--- clang-tidy/cert/CERTTidyModule.cpp
+++ clang-tidy/cert/CERTTidyModule.cpp
@@ -43,6 +43,8 @@
 CheckFactories.registerCheck(
 "cert-oop11-cpp");
 // ERR
+CheckFactories.registerCheck(
+"cert-err09-cpp");
 CheckFactories.registerCheck(
 "cert-err52-cpp");
 CheckFactories.registerCheck(


Index: docs/clang-tidy/checks/misc-throw-by-value-catch-by-reference.rst
===
--- docs/clang-tidy/checks/misc-throw-by-value-catch-by-reference.rst
+++ docs/clang-tidy/checks/misc-throw-by-value-catch-by-reference.rst
@@ -3,6 +3,7 @@
 misc-throw-by-value-catch-by-reference
 ==
 
+"cert-err09-cpp" redirects here as an alias for this check.
 "cert-err61-cpp" redirects here as an alias for this check.
 
 Finds violations of the rule "Throw by value, catch by reference" presented for
Index: docs/clang-tidy/checks/list.rst
===
--- docs/clang-tidy/checks/list.rst
+++ docs/clang-tidy/checks/list.rst
@@ -10,6 +10,7 @@
cert-dcl54-cpp (redirects to misc-new-delete-overloads) 
cert-dcl59-cpp (redirects to google-build-namespaces) 
cert-env33-c
+   cert-err09-cpp (redirects to misc-throw-by-value-catch-by-reference) 
cert-err34-c
cert-err52-cpp
cert-err58-cpp
Index: docs/clang-tidy/checks/cert-err09-cpp.rst
===
--- /dev/null
+++ docs/clang-tidy/checks/cert-err09-cpp.rst
@@ -0,0 +1,10 @@
+.. title:: clang-tidy - cert-err09-cpp
+.. meta::
+   :http-equiv=refresh: 5;URL=misc-throw-by-value-catch-by-reference.html
+
+cert-err09-cpp
+==
+
+The cert-err09-cpp check is an alias, please see
+`misc-throw-by-value-catch-by-reference `_
+for more information.
Index: clang-tidy/cert/CERTTidyModule.cpp
===
--- clang-tidy/cert/CERTTidyModule.cpp
+++ clang-tidy/cert/CERTTidyModule.cpp
@@ -43,6 +43,8 @@
 CheckFactories.registerCheck(
 "cert-oop11-cpp");
 // ERR
+CheckFactories.registerCheck(
+"cert-err09-cpp");
 CheckFactories.registerCheck(
 "cert-err52-cpp");
 CheckFactories.registerCheck(
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] r284596 - [clang-tidy] Add cert-err09-cpp check alias.

2016-10-19 Thread Marek Kurdej via cfe-commits
Author: mkurdej
Date: Wed Oct 19 09:28:19 2016
New Revision: 284596

URL: http://llvm.org/viewvc/llvm-project?rev=284596&view=rev
Log:
[clang-tidy] Add cert-err09-cpp check alias.

Summary: This adds cert-err09-cpp alias for completeness, similar to 
cert-err61-cpp.

Reviewers: alexfh, hokein

Subscribers: cfe-commits

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

Added:
clang-tools-extra/trunk/docs/clang-tidy/checks/cert-err09-cpp.rst
Modified:
clang-tools-extra/trunk/clang-tidy/cert/CERTTidyModule.cpp
clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst

clang-tools-extra/trunk/docs/clang-tidy/checks/misc-throw-by-value-catch-by-reference.rst

Modified: clang-tools-extra/trunk/clang-tidy/cert/CERTTidyModule.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/cert/CERTTidyModule.cpp?rev=284596&r1=284595&r2=284596&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/cert/CERTTidyModule.cpp (original)
+++ clang-tools-extra/trunk/clang-tidy/cert/CERTTidyModule.cpp Wed Oct 19 
09:28:19 2016
@@ -43,6 +43,8 @@ public:
 CheckFactories.registerCheck(
 "cert-oop11-cpp");
 // ERR
+CheckFactories.registerCheck(
+"cert-err09-cpp");
 CheckFactories.registerCheck(
 "cert-err52-cpp");
 CheckFactories.registerCheck(

Added: clang-tools-extra/trunk/docs/clang-tidy/checks/cert-err09-cpp.rst
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/docs/clang-tidy/checks/cert-err09-cpp.rst?rev=284596&view=auto
==
--- clang-tools-extra/trunk/docs/clang-tidy/checks/cert-err09-cpp.rst (added)
+++ clang-tools-extra/trunk/docs/clang-tidy/checks/cert-err09-cpp.rst Wed Oct 
19 09:28:19 2016
@@ -0,0 +1,10 @@
+.. title:: clang-tidy - cert-err09-cpp
+.. meta::
+   :http-equiv=refresh: 5;URL=misc-throw-by-value-catch-by-reference.html
+
+cert-err09-cpp
+==
+
+The cert-err09-cpp check is an alias, please see
+`misc-throw-by-value-catch-by-reference 
`_
+for more information.

Modified: clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst?rev=284596&r1=284595&r2=284596&view=diff
==
--- clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst (original)
+++ clang-tools-extra/trunk/docs/clang-tidy/checks/list.rst Wed Oct 19 09:28:19 
2016
@@ -10,6 +10,7 @@ Clang-Tidy Checks
cert-dcl54-cpp (redirects to misc-new-delete-overloads) 
cert-dcl59-cpp (redirects to google-build-namespaces) 
cert-env33-c
+   cert-err09-cpp (redirects to misc-throw-by-value-catch-by-reference) 

cert-err34-c
cert-err52-cpp
cert-err58-cpp

Modified: 
clang-tools-extra/trunk/docs/clang-tidy/checks/misc-throw-by-value-catch-by-reference.rst
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/docs/clang-tidy/checks/misc-throw-by-value-catch-by-reference.rst?rev=284596&r1=284595&r2=284596&view=diff
==
--- 
clang-tools-extra/trunk/docs/clang-tidy/checks/misc-throw-by-value-catch-by-reference.rst
 (original)
+++ 
clang-tools-extra/trunk/docs/clang-tidy/checks/misc-throw-by-value-catch-by-reference.rst
 Wed Oct 19 09:28:19 2016
@@ -3,6 +3,7 @@
 misc-throw-by-value-catch-by-reference
 ==
 
+"cert-err09-cpp" redirects here as an alias for this check.
 "cert-err61-cpp" redirects here as an alias for this check.
 
 Finds violations of the rule "Throw by value, catch by reference" presented for


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


[clang-tools-extra] r247536 - Test commit.

2015-09-14 Thread Marek Kurdej via cfe-commits
Author: mkurdej
Date: Mon Sep 14 03:05:12 2015
New Revision: 247536

URL: http://llvm.org/viewvc/llvm-project?rev=247536&view=rev
Log:
Test commit.

Modified:
clang-tools-extra/trunk/clang-tidy/ClangTidyDiagnosticConsumer.cpp

Modified: clang-tools-extra/trunk/clang-tidy/ClangTidyDiagnosticConsumer.cpp
URL: 
http://llvm.org/viewvc/llvm-project/clang-tools-extra/trunk/clang-tidy/ClangTidyDiagnosticConsumer.cpp?rev=247536&r1=247535&r2=247536&view=diff
==
--- clang-tools-extra/trunk/clang-tidy/ClangTidyDiagnosticConsumer.cpp 
(original)
+++ clang-tools-extra/trunk/clang-tidy/ClangTidyDiagnosticConsumer.cpp Mon Sep 
14 03:05:12 2015
@@ -56,8 +56,7 @@ protected:
   Error.Notes.push_back(TidyMessage);
   return;
 }
-assert(Error.Message.Message.empty() &&
-   "Overwriting a diagnostic message");
+assert(Error.Message.Message.empty() && "Overwriting a diagnostic 
message");
 Error.Message = TidyMessage;
   }
 


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


Re: [PATCH] D13549: Added new options to ClangFormat VSIX package.

2015-10-08 Thread Marek Kurdej via cfe-commits
curdeius updated this revision to Diff 36849.
curdeius added a comment.

Escape XML-reserved characters.


http://reviews.llvm.org/D13549

Files:
  tools/clang-format-vs/ClangFormat/ClangFormatPackage.cs
  tools/clang-format-vs/ClangFormat/Properties/AssemblyInfo.cs
  tools/clang-format/ClangFormat.cpp

Index: tools/clang-format/ClangFormat.cpp
===
--- tools/clang-format/ClangFormat.cpp
+++ tools/clang-format/ClangFormat.cpp
@@ -201,15 +201,30 @@
 static void outputReplacementXML(StringRef Text) {
   size_t From = 0;
   size_t Index;
-  while ((Index = Text.find_first_of("\n\r", From)) != StringRef::npos) {
+  while ((Index = Text.find_first_of("\n\r<>&\"'", From)) != StringRef::npos) {
 llvm::outs() << Text.substr(From, Index - From);
 switch (Text[Index]) {
 case '\n':
   llvm::outs() << "
";
   break;
 case '\r':
   llvm::outs() << "
";
   break;
+case '<':
+  llvm::outs() << "<";
+  break;
+case '>':
+  llvm::outs() << ">";
+  break;
+case '&':
+  llvm::outs() << "&";
+  break;
+case '\'':
+  llvm::outs() << "'";
+  break;
+case '"':
+  llvm::outs() << """;
+  break;
 default:
   llvm_unreachable("Unexpected character encountered!");
 }
Index: tools/clang-format-vs/ClangFormat/Properties/AssemblyInfo.cs
===
--- tools/clang-format-vs/ClangFormat/Properties/AssemblyInfo.cs
+++ tools/clang-format-vs/ClangFormat/Properties/AssemblyInfo.cs
@@ -29,5 +29,5 @@
 // You can specify all the values or you can default the Revision and Build Numbers 
 // by using the '*' as shown below:
 
-[assembly: AssemblyVersion("1.0.0.0")]
-[assembly: AssemblyFileVersion("1.0.0.0")]
+[assembly: AssemblyVersion("1.1.0.0")]
+[assembly: AssemblyFileVersion("1.1.0.0")]
Index: tools/clang-format-vs/ClangFormat/ClangFormatPackage.cs
===
--- tools/clang-format-vs/ClangFormat/ClangFormatPackage.cs
+++ tools/clang-format-vs/ClangFormat/ClangFormatPackage.cs
@@ -32,13 +32,16 @@
 [CLSCompliant(false), ComVisible(true)]
 public class OptionPageGrid : DialogPage
 {
-private string style = "File";
+private string assumeFilename = "";
+private string fallbackStyle = "LLVM";
+private bool sortIncludes = false;
+private string style = "file";
 
 [Category("LLVM/Clang")]
 [DisplayName("Style")]
 [Description("Coding style, currently supports:\n" +
- "  - Predefined styles ('LLVM', 'Google', 'Chromium', 'Mozilla').\n" +
- "  - 'File' to search for a YAML .clang-format or _clang-format\n" +
+ "  - Predefined styles ('LLVM', 'Google', 'Chromium', 'Mozilla', 'WebKit').\n" +
+ "  - 'file' to search for a YAML .clang-format or _clang-format\n" +
  "configuration file.\n" +
  "  - A YAML configuration snippet.\n\n" +
  "'File':\n" +
@@ -53,6 +56,38 @@
 get { return style; }
 set { style = value; }
 }
+
+[Category("LLVM/Clang")]
+[DisplayName("Assume Filename")]
+[Description("When reading from stdin, clang-format assumes this " +
+ "filename to look for a style config file (with 'file' style) \n" +
+ "and to determine the language.")]
+public string AssumeFilename
+{
+get { return assumeFilename; }
+set { assumeFilename = value; }
+}
+
+[Category("LLVM/Clang")]
+[DisplayName("Fallback Style")]
+[Description("The name of the predefined style used as a fallback in case clang-format " +
+ "is invoked with 'file' style, but can not find the configuration file.\n" +
+ "Use 'none' fallback style to skip formatting.")]
+public string FallbackStyle
+{
+get { return fallbackStyle; }
+set { fallbackStyle = value; }
+}
+
+[Category("LLVM/Clang")]
+[DisplayName("Sort includes")]
+[Description("Sort touched include lines.\n\n" +
+ "See also: http://clang.llvm.org/docs/ClangFormat.html.";)]
+public bool SortIncludes
+{
+get { return sortIncludes; }
+set { sortIncludes = value; }
+}
 }
 
 [PackageRegistration(UseManagedResourcesOnly = true)]
@@ -138,10 +173,17 @@
 // Poor man's escaping - this will not work when quotes are already escaped
 // in the input (but we don't need more).
 string style = GetStyle().Replace("\"", "\\\"");
+string fallbackStyle = GetFallbackStyle().Replace("\"", "\\\"");
 process.StartInfo.Arguments = " -offset " + offset +
 

Re: [PATCH] D13549: Added new options to ClangFormat VSIX package.

2015-10-12 Thread Marek Kurdej via cfe-commits
curdeius updated this revision to Diff 37081.
curdeius added a comment.

Fix description formatting.


http://reviews.llvm.org/D13549

Files:
  lib/Driver/Tools.cpp
  tools/clang-format-vs/ClangFormat/ClangFormatPackage.cs
  tools/clang-format-vs/ClangFormat/Properties/AssemblyInfo.cs
  tools/clang-format/ClangFormat.cpp

Index: tools/clang-format/ClangFormat.cpp
===
--- tools/clang-format/ClangFormat.cpp
+++ tools/clang-format/ClangFormat.cpp
@@ -201,15 +201,30 @@
 static void outputReplacementXML(StringRef Text) {
   size_t From = 0;
   size_t Index;
-  while ((Index = Text.find_first_of("\n\r", From)) != StringRef::npos) {
+  while ((Index = Text.find_first_of("\n\r<>&\"'", From)) != StringRef::npos) {
 llvm::outs() << Text.substr(From, Index - From);
 switch (Text[Index]) {
 case '\n':
   llvm::outs() << "
";
   break;
 case '\r':
   llvm::outs() << "
";
   break;
+case '<':
+  llvm::outs() << "<";
+  break;
+case '>':
+  llvm::outs() << ">";
+  break;
+case '&':
+  llvm::outs() << "&";
+  break;
+case '\'':
+  llvm::outs() << "'";
+  break;
+case '"':
+  llvm::outs() << """;
+  break;
 default:
   llvm_unreachable("Unexpected character encountered!");
 }
Index: tools/clang-format-vs/ClangFormat/Properties/AssemblyInfo.cs
===
--- tools/clang-format-vs/ClangFormat/Properties/AssemblyInfo.cs
+++ tools/clang-format-vs/ClangFormat/Properties/AssemblyInfo.cs
@@ -29,5 +29,5 @@
 // You can specify all the values or you can default the Revision and Build Numbers 
 // by using the '*' as shown below:
 
-[assembly: AssemblyVersion("1.0.0.0")]
-[assembly: AssemblyFileVersion("1.0.0.0")]
+[assembly: AssemblyVersion("1.1.0.0")]
+[assembly: AssemblyFileVersion("1.1.0.0")]
Index: tools/clang-format-vs/ClangFormat/ClangFormatPackage.cs
===
--- tools/clang-format-vs/ClangFormat/ClangFormatPackage.cs
+++ tools/clang-format-vs/ClangFormat/ClangFormatPackage.cs
@@ -32,13 +32,16 @@
 [CLSCompliant(false), ComVisible(true)]
 public class OptionPageGrid : DialogPage
 {
-private string style = "File";
+private string assumeFilename = "";
+private string fallbackStyle = "LLVM";
+private bool sortIncludes = false;
+private string style = "file";
 
 [Category("LLVM/Clang")]
 [DisplayName("Style")]
 [Description("Coding style, currently supports:\n" +
- "  - Predefined styles ('LLVM', 'Google', 'Chromium', 'Mozilla').\n" +
- "  - 'File' to search for a YAML .clang-format or _clang-format\n" +
+ "  - Predefined styles ('LLVM', 'Google', 'Chromium', 'Mozilla', 'WebKit').\n" +
+ "  - 'file' to search for a YAML .clang-format or _clang-format\n" +
  "configuration file.\n" +
  "  - A YAML configuration snippet.\n\n" +
  "'File':\n" +
@@ -53,6 +56,38 @@
 get { return style; }
 set { style = value; }
 }
+
+[Category("LLVM/Clang")]
+[DisplayName("Assume Filename")]
+[Description("When reading from stdin, clang-format assumes this " +
+ "filename to look for a style config file (with 'file' style) " +
+ "and to determine the language.")]
+public string AssumeFilename
+{
+get { return assumeFilename; }
+set { assumeFilename = value; }
+}
+
+[Category("LLVM/Clang")]
+[DisplayName("Fallback Style")]
+[Description("The name of the predefined style used as a fallback in case clang-format " +
+ "is invoked with 'file' style, but can not find the configuration file.\n" +
+ "Use 'none' fallback style to skip formatting.")]
+public string FallbackStyle
+{
+get { return fallbackStyle; }
+set { fallbackStyle = value; }
+}
+
+[Category("LLVM/Clang")]
+[DisplayName("Sort includes")]
+[Description("Sort touched include lines.\n\n" +
+ "See also: http://clang.llvm.org/docs/ClangFormat.html.";)]
+public bool SortIncludes
+{
+get { return sortIncludes; }
+set { sortIncludes = value; }
+}
 }
 
 [PackageRegistration(UseManagedResourcesOnly = true)]
@@ -138,10 +173,17 @@
 // Poor man's escaping - this will not work when quotes are already escaped
 // in the input (but we don't need more).
 string style = GetStyle().Replace("\"", "\\\"");
+string fallbackStyle = GetFallbackStyle().Replace("\"", "\\\"");
 process.StartInfo.Arguments = " -offset "

Re: [PATCH] D13549: Added new options to ClangFormat VSIX package.

2015-10-12 Thread Marek Kurdej via cfe-commits
curdeius added inline comments.


Comment at: lib/Driver/Tools.cpp:2356
@@ -2355,3 +2355,3 @@
 CmdArgs.push_back(
-Args.MakeArgString("-dwarf-version=" + llvm::itostr(DwarfVersion)));
+Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
 }

klimek wrote:
> Seems unrelated?
Oups, I've made a mistake when updating the revision and pulled in the changes 
from master.
I'll correct this.


Comment at: tools/clang-format/ClangFormat.cpp:227
@@ -213,1 +226,3 @@
+  llvm::outs() << """;
+  break;
 default:

klimek wrote:
> For XML, we should only need "<" and "&". Everything else is just important 
> in a context introduced by "<" or "&".
> The problem with include-sorting is that we'll now need to fully support utf8 
> input (well, any encoding, to be precise).
> The best way is probably to escape all code points that are outside the ascii 
> range. The problem I see is that we have no idea what encoding the file is 
> in, so I have no clue how we can really resolve this.
> 
Ok. I'll cut it  down to the necessary minimum ('<', '&').
Anyway, I thing it's more urgent to fix the include sorting containing open 
brackets and later work on UTF-8 support.


http://reviews.llvm.org/D13549



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


Re: [PATCH] D13549: Added new options to ClangFormat VSIX package.

2015-10-12 Thread Marek Kurdej via cfe-commits
curdeius updated this revision to Diff 37086.
curdeius added a comment.

Escape only '<' and '&'.
Remove unrelated changes from the revision.


http://reviews.llvm.org/D13549

Files:
  tools/clang-format-vs/ClangFormat/ClangFormatPackage.cs
  tools/clang-format-vs/ClangFormat/Properties/AssemblyInfo.cs
  tools/clang-format/ClangFormat.cpp

Index: tools/clang-format/ClangFormat.cpp
===
--- tools/clang-format/ClangFormat.cpp
+++ tools/clang-format/ClangFormat.cpp
@@ -201,15 +201,21 @@
 static void outputReplacementXML(StringRef Text) {
   size_t From = 0;
   size_t Index;
-  while ((Index = Text.find_first_of("\n\r", From)) != StringRef::npos) {
+  while ((Index = Text.find_first_of("\n\r<&", From)) != StringRef::npos) {
 llvm::outs() << Text.substr(From, Index - From);
 switch (Text[Index]) {
 case '\n':
   llvm::outs() << "
";
   break;
 case '\r':
   llvm::outs() << "
";
   break;
+case '<':
+  llvm::outs() << "<";
+  break;
+case '&':
+  llvm::outs() << "&";
+  break;
 default:
   llvm_unreachable("Unexpected character encountered!");
 }
Index: tools/clang-format-vs/ClangFormat/Properties/AssemblyInfo.cs
===
--- tools/clang-format-vs/ClangFormat/Properties/AssemblyInfo.cs
+++ tools/clang-format-vs/ClangFormat/Properties/AssemblyInfo.cs
@@ -29,5 +29,5 @@
 // You can specify all the values or you can default the Revision and Build Numbers 
 // by using the '*' as shown below:
 
-[assembly: AssemblyVersion("1.0.0.0")]
-[assembly: AssemblyFileVersion("1.0.0.0")]
+[assembly: AssemblyVersion("1.1.0.0")]
+[assembly: AssemblyFileVersion("1.1.0.0")]
Index: tools/clang-format-vs/ClangFormat/ClangFormatPackage.cs
===
--- tools/clang-format-vs/ClangFormat/ClangFormatPackage.cs
+++ tools/clang-format-vs/ClangFormat/ClangFormatPackage.cs
@@ -32,13 +32,16 @@
 [CLSCompliant(false), ComVisible(true)]
 public class OptionPageGrid : DialogPage
 {
-private string style = "File";
+private string assumeFilename = "";
+private string fallbackStyle = "LLVM";
+private bool sortIncludes = false;
+private string style = "file";
 
 [Category("LLVM/Clang")]
 [DisplayName("Style")]
 [Description("Coding style, currently supports:\n" +
- "  - Predefined styles ('LLVM', 'Google', 'Chromium', 'Mozilla').\n" +
- "  - 'File' to search for a YAML .clang-format or _clang-format\n" +
+ "  - Predefined styles ('LLVM', 'Google', 'Chromium', 'Mozilla', 'WebKit').\n" +
+ "  - 'file' to search for a YAML .clang-format or _clang-format\n" +
  "configuration file.\n" +
  "  - A YAML configuration snippet.\n\n" +
  "'File':\n" +
@@ -53,6 +56,38 @@
 get { return style; }
 set { style = value; }
 }
+
+[Category("LLVM/Clang")]
+[DisplayName("Assume Filename")]
+[Description("When reading from stdin, clang-format assumes this " +
+ "filename to look for a style config file (with 'file' style) " +
+ "and to determine the language.")]
+public string AssumeFilename
+{
+get { return assumeFilename; }
+set { assumeFilename = value; }
+}
+
+[Category("LLVM/Clang")]
+[DisplayName("Fallback Style")]
+[Description("The name of the predefined style used as a fallback in case clang-format " +
+ "is invoked with 'file' style, but can not find the configuration file.\n" +
+ "Use 'none' fallback style to skip formatting.")]
+public string FallbackStyle
+{
+get { return fallbackStyle; }
+set { fallbackStyle = value; }
+}
+
+[Category("LLVM/Clang")]
+[DisplayName("Sort includes")]
+[Description("Sort touched include lines.\n\n" +
+ "See also: http://clang.llvm.org/docs/ClangFormat.html.";)]
+public bool SortIncludes
+{
+get { return sortIncludes; }
+set { sortIncludes = value; }
+}
 }
 
 [PackageRegistration(UseManagedResourcesOnly = true)]
@@ -138,10 +173,17 @@
 // Poor man's escaping - this will not work when quotes are already escaped
 // in the input (but we don't need more).
 string style = GetStyle().Replace("\"", "\\\"");
+string fallbackStyle = GetFallbackStyle().Replace("\"", "\\\"");
 process.StartInfo.Arguments = " -offset " + offset +
   " -length " + length +
   " -output-replacements-xml " +
- 

Re: [PATCH] D13549: Added new options to ClangFormat VSIX package.

2015-10-12 Thread Marek Kurdej via cfe-commits
curdeius updated this revision to Diff 37087.
curdeius marked 2 inline comments as done.
curdeius added a comment.

Add FIXME comment.


http://reviews.llvm.org/D13549

Files:
  tools/clang-format-vs/ClangFormat/ClangFormatPackage.cs
  tools/clang-format-vs/ClangFormat/Properties/AssemblyInfo.cs
  tools/clang-format/ClangFormat.cpp

Index: tools/clang-format/ClangFormat.cpp
===
--- tools/clang-format/ClangFormat.cpp
+++ tools/clang-format/ClangFormat.cpp
@@ -199,17 +199,25 @@
 }
 
 static void outputReplacementXML(StringRef Text) {
+  // FIXME: When we sort includes, we need to make sure the stream is correct
+  // utf-8.
   size_t From = 0;
   size_t Index;
-  while ((Index = Text.find_first_of("\n\r", From)) != StringRef::npos) {
+  while ((Index = Text.find_first_of("\n\r<&", From)) != StringRef::npos) {
 llvm::outs() << Text.substr(From, Index - From);
 switch (Text[Index]) {
 case '\n':
   llvm::outs() << "
";
   break;
 case '\r':
   llvm::outs() << "
";
   break;
+case '<':
+  llvm::outs() << "<";
+  break;
+case '&':
+  llvm::outs() << "&";
+  break;
 default:
   llvm_unreachable("Unexpected character encountered!");
 }
Index: tools/clang-format-vs/ClangFormat/Properties/AssemblyInfo.cs
===
--- tools/clang-format-vs/ClangFormat/Properties/AssemblyInfo.cs
+++ tools/clang-format-vs/ClangFormat/Properties/AssemblyInfo.cs
@@ -29,5 +29,5 @@
 // You can specify all the values or you can default the Revision and Build Numbers 
 // by using the '*' as shown below:
 
-[assembly: AssemblyVersion("1.0.0.0")]
-[assembly: AssemblyFileVersion("1.0.0.0")]
+[assembly: AssemblyVersion("1.1.0.0")]
+[assembly: AssemblyFileVersion("1.1.0.0")]
Index: tools/clang-format-vs/ClangFormat/ClangFormatPackage.cs
===
--- tools/clang-format-vs/ClangFormat/ClangFormatPackage.cs
+++ tools/clang-format-vs/ClangFormat/ClangFormatPackage.cs
@@ -32,13 +32,16 @@
 [CLSCompliant(false), ComVisible(true)]
 public class OptionPageGrid : DialogPage
 {
-private string style = "File";
+private string assumeFilename = "";
+private string fallbackStyle = "LLVM";
+private bool sortIncludes = false;
+private string style = "file";
 
 [Category("LLVM/Clang")]
 [DisplayName("Style")]
 [Description("Coding style, currently supports:\n" +
- "  - Predefined styles ('LLVM', 'Google', 'Chromium', 'Mozilla').\n" +
- "  - 'File' to search for a YAML .clang-format or _clang-format\n" +
+ "  - Predefined styles ('LLVM', 'Google', 'Chromium', 'Mozilla', 'WebKit').\n" +
+ "  - 'file' to search for a YAML .clang-format or _clang-format\n" +
  "configuration file.\n" +
  "  - A YAML configuration snippet.\n\n" +
  "'File':\n" +
@@ -53,6 +56,38 @@
 get { return style; }
 set { style = value; }
 }
+
+[Category("LLVM/Clang")]
+[DisplayName("Assume Filename")]
+[Description("When reading from stdin, clang-format assumes this " +
+ "filename to look for a style config file (with 'file' style) " +
+ "and to determine the language.")]
+public string AssumeFilename
+{
+get { return assumeFilename; }
+set { assumeFilename = value; }
+}
+
+[Category("LLVM/Clang")]
+[DisplayName("Fallback Style")]
+[Description("The name of the predefined style used as a fallback in case clang-format " +
+ "is invoked with 'file' style, but can not find the configuration file.\n" +
+ "Use 'none' fallback style to skip formatting.")]
+public string FallbackStyle
+{
+get { return fallbackStyle; }
+set { fallbackStyle = value; }
+}
+
+[Category("LLVM/Clang")]
+[DisplayName("Sort includes")]
+[Description("Sort touched include lines.\n\n" +
+ "See also: http://clang.llvm.org/docs/ClangFormat.html.";)]
+public bool SortIncludes
+{
+get { return sortIncludes; }
+set { sortIncludes = value; }
+}
 }
 
 [PackageRegistration(UseManagedResourcesOnly = true)]
@@ -138,10 +173,17 @@
 // Poor man's escaping - this will not work when quotes are already escaped
 // in the input (but we don't need more).
 string style = GetStyle().Replace("\"", "\\\"");
+string fallbackStyle = GetFallbackStyle().Replace("\"", "\\\"");
 process.StartInfo.Arguments = " -offset " + offset +
   " -length " +

Re: [PATCH] D13549: Added new options to ClangFormat VSIX package.

2015-10-12 Thread Marek Kurdej via cfe-commits
curdeius marked 3 inline comments as done.
curdeius added a comment.

Applied suggestions from comments.


http://reviews.llvm.org/D13549



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


Re: [PATCH] D13549: Added new options to ClangFormat VSIX package.

2015-10-12 Thread Marek Kurdej via cfe-commits
curdeius added inline comments.


Comment at: tools/clang-format-vs/ClangFormat/ClangFormatPackage.cs:186
@@ -145,1 +185,3 @@
+if (!string.IsNullOrEmpty(assumeFilename))
+  process.StartInfo.Arguments += " -assume-filename \"" + 
assumeFilename + "\"";
 process.StartInfo.CreateNoWindow = true;

klimek wrote:
> Don't we need " escaping for assumeFilename? (or do we consider that an 
> error? in which case, would we want to make that an error?)
Well, quotes (") are not allowed as a part of a file name on Windows.
What we could do is to strip surrounding quotes if the user added them in order 
not to add them twice.


http://reviews.llvm.org/D13549



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


Re: [PATCH] D13549: Added new options to ClangFormat VSIX package.

2015-10-12 Thread Marek Kurdej via cfe-commits
curdeius added inline comments.


Comment at: tools/clang-format-vs/ClangFormat/ClangFormatPackage.cs:186
@@ -145,1 +185,3 @@
+if (!string.IsNullOrEmpty(assumeFilename))
+  process.StartInfo.Arguments += " -assume-filename \"" + 
assumeFilename + "\"";
 process.StartInfo.CreateNoWindow = true;

klimek wrote:
> curdeius wrote:
> > klimek wrote:
> > > Don't we need " escaping for assumeFilename? (or do we consider that an 
> > > error? in which case, would we want to make that an error?)
> > Well, quotes (") are not allowed as a part of a file name on Windows.
> > What we could do is to strip surrounding quotes if the user added them in 
> > order not to add them twice.
> Oh, I didn't know that.
> My main concern is what happens when the user (accidentally) adds quotes (for 
> example, unbalanced) and messes up the command line in a way that leads to a 
> super hard to diagnose problem
Hmm, you're right, we should do something with that.
Either:

  - escape all quotes (but then the errors will be silent and user will not 
know that something bad happens)
  - or to give an error message somehow, e.g. by using a custom TypeConverter 
for AssumeFilename option that will check for the existence of quotes.


http://reviews.llvm.org/D13549



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


Re: [PATCH] D13549: Added new options to ClangFormat VSIX package.

2015-10-12 Thread Marek Kurdej via cfe-commits
curdeius marked 5 inline comments as done.
curdeius added a comment.

Assume-Filename option will now give an error when there are quotes in the 
filename.


http://reviews.llvm.org/D13549



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


  1   2   3   >