r185914 - Fix alignment of closing brace in braced initializers.

Daniel Jasper djasper at google.com
Tue Jul 9 02:06:30 PDT 2013


Author: djasper
Date: Tue Jul  9 04:06:29 2013
New Revision: 185914

URL: http://llvm.org/viewvc/llvm-project?rev=185914&view=rev
Log:
Fix alignment of closing brace in braced initializers.

Before:
someFunction(OtherParam, BracedList{
                           // comment 1 (Forcing intersting break)
                           param1, param2,
                           // comment 2
                           param3, param4
             });
After:
someFunction(OtherParam, BracedList{
                           // comment 1 (Forcing intersting break)
                           param1, param2,
                           // comment 2
                           param3, param4
                         });

To do so, the UnwrappedLineParser now stores the information about the
kind of brace in the FormatToken.

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

Modified: cfe/trunk/lib/Format/Format.cpp
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/Format.cpp?rev=185914&r1=185913&r2=185914&view=diff
==============================================================================
--- cfe/trunk/lib/Format/Format.cpp (original)
+++ cfe/trunk/lib/Format/Format.cpp Tue Jul  9 04:06:29 2013
@@ -514,7 +514,10 @@ private:
     if (Newline) {
       State.Stack.back().ContainsLineBreak = true;
       if (Current.is(tok::r_brace)) {
-        State.Column = Line.Level * Style.IndentWidth;
+        if (Current.BlockKind == BK_BracedInit)
+          State.Column = State.Stack[State.Stack.size() - 2].LastSpace;
+        else
+          State.Column = Line.Level * Style.IndentWidth;
       } else if (Current.is(tok::string_literal) &&
                  State.StartOfStringLiteral != 0) {
         State.Column = State.StartOfStringLiteral;

Modified: cfe/trunk/lib/Format/FormatToken.h
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/FormatToken.h?rev=185914&r1=185913&r2=185914&view=diff
==============================================================================
--- cfe/trunk/lib/Format/FormatToken.h (original)
+++ cfe/trunk/lib/Format/FormatToken.h Tue Jul  9 04:06:29 2013
@@ -56,16 +56,24 @@ enum TokenType {
   TT_Unknown
 };
 
+// Represents what type of block a set of braces open.
+enum BraceBlockKind {
+  BK_Unknown,
+  BK_Block,
+  BK_BracedInit
+};
+
 /// \brief A wrapper around a \c Token storing information about the
 /// whitespace characters preceeding it.
 struct FormatToken {
   FormatToken()
       : NewlinesBefore(0), HasUnescapedNewline(false), LastNewlineOffset(0),
         CodePointCount(0), IsFirst(false), MustBreakBefore(false),
-        Type(TT_Unknown), SpacesRequiredBefore(0), CanBreakBefore(false),
-        ClosesTemplateDeclaration(false), ParameterCount(0), TotalLength(0),
-        UnbreakableTailLength(0), BindingStrength(0), SplitPenalty(0),
-        LongestObjCSelectorName(0), FakeRParens(0), LastInChainOfCalls(false),
+        BlockKind(BK_Unknown), Type(TT_Unknown), SpacesRequiredBefore(0),
+        CanBreakBefore(false), ClosesTemplateDeclaration(false),
+        ParameterCount(0), TotalLength(0), UnbreakableTailLength(0),
+        BindingStrength(0), SplitPenalty(0), LongestObjCSelectorName(0),
+        FakeRParens(0), LastInChainOfCalls(false),
         PartOfMultiVariableDeclStmt(false), MatchingParen(NULL), Previous(NULL),
         Next(NULL) {}
 
@@ -117,6 +125,9 @@ struct FormatToken {
   /// escaped newlines.
   StringRef TokenText;
 
+  /// \brief Contains the kind of block if this token is a brace.
+  BraceBlockKind BlockKind;
+
   TokenType Type;
 
   unsigned SpacesRequiredBefore;

Modified: cfe/trunk/lib/Format/UnwrappedLineParser.cpp
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/UnwrappedLineParser.cpp?rev=185914&r1=185913&r2=185914&view=diff
==============================================================================
--- cfe/trunk/lib/Format/UnwrappedLineParser.cpp (original)
+++ cfe/trunk/lib/Format/UnwrappedLineParser.cpp Tue Jul  9 04:06:29 2013
@@ -183,9 +183,7 @@ UnwrappedLineParser::UnwrappedLineParser
                                          UnwrappedLineConsumer &Callback)
     : Line(new UnwrappedLine), MustBreakBeforeNextToken(false),
       CurrentLines(&Lines), StructuralError(false), Style(Style), Tokens(NULL),
-      Callback(Callback), AllTokens(Tokens) {
-  LBraces.resize(Tokens.size(), BS_Unknown);
-}
+      Callback(Callback), AllTokens(Tokens) {}
 
 bool UnwrappedLineParser::parse() {
   DEBUG(llvm::dbgs() << "----\n");
@@ -252,7 +250,7 @@ void UnwrappedLineParser::calculateBrace
   // Keep a stack of positions of lbrace tokens. We will
   // update information about whether an lbrace starts a
   // braced init list or a different block during the loop.
-  SmallVector<unsigned, 8> LBraceStack;
+  SmallVector<FormatToken *, 8> LBraceStack;
   assert(Tok->Tok.is(tok::l_brace));
   do {
     // Get next none-comment token.
@@ -265,11 +263,11 @@ void UnwrappedLineParser::calculateBrace
 
     switch (Tok->Tok.getKind()) {
     case tok::l_brace:
-      LBraceStack.push_back(Position);
+      LBraceStack.push_back(Tok);
       break;
     case tok::r_brace:
       if (!LBraceStack.empty()) {
-        if (LBraces[LBraceStack.back()] == BS_Unknown) {
+        if (LBraceStack.back()->BlockKind == BK_Unknown) {
           // If there is a comma, semicolon or right paren after the closing
           // brace, we assume this is a braced initializer list.
 
@@ -279,10 +277,13 @@ void UnwrappedLineParser::calculateBrace
           // brace blocks inside it braced init list. That works good enough
           // for now, but we will need to fix it to correctly handle lambdas.
           if (NextTok->isOneOf(tok::comma, tok::semi, tok::r_paren,
-                               tok::l_brace, tok::colon))
-            LBraces[LBraceStack.back()] = BS_BracedInit;
-          else
-            LBraces[LBraceStack.back()] = BS_Block;
+                               tok::l_brace, tok::colon)) {
+            Tok->BlockKind = BK_BracedInit;
+            LBraceStack.back()->BlockKind = BK_BracedInit;
+          } else {
+            Tok->BlockKind = BK_Block;
+            LBraceStack.back()->BlockKind = BK_Block;
+          }
         }
         LBraceStack.pop_back();
       }
@@ -294,7 +295,7 @@ void UnwrappedLineParser::calculateBrace
     case tok::kw_switch:
     case tok::kw_try:
       if (!LBraceStack.empty())
-        LBraces[LBraceStack.back()] = BS_Block;
+        LBraceStack.back()->BlockKind = BK_Block;
       break;
     default:
       break;
@@ -304,8 +305,8 @@ void UnwrappedLineParser::calculateBrace
   } while (Tok->Tok.isNot(tok::eof));
   // Assume other blocks for all unclosed opening braces.
   for (unsigned i = 0, e = LBraceStack.size(); i != e; ++i) {
-    if (LBraces[LBraceStack[i]] == BS_Unknown)
-      LBraces[LBraceStack[i]] = BS_Block;
+    if (LBraceStack[i]->BlockKind == BK_Unknown)
+      LBraceStack[i]->BlockKind = BK_Block;
   }
   FormatTok = Tokens->setPosition(StoredPosition);
 }
@@ -632,10 +633,10 @@ void UnwrappedLineParser::parseStructura
 }
 
 bool UnwrappedLineParser::tryToParseBracedList() {
-  if (LBraces[Tokens->getPosition()] == BS_Unknown)
+  if (FormatTok->BlockKind == BK_Unknown)
     calculateBraceTypes();
-  assert(LBraces[Tokens->getPosition()] != BS_Unknown);
-  if (LBraces[Tokens->getPosition()] == BS_Block)
+  assert(FormatTok->BlockKind != BK_Unknown);
+  if (FormatTok->BlockKind == BK_Block)
     return false;
   parseBracedList();
   return true;

Modified: cfe/trunk/lib/Format/UnwrappedLineParser.h
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/UnwrappedLineParser.h?rev=185914&r1=185913&r2=185914&view=diff
==============================================================================
--- cfe/trunk/lib/Format/UnwrappedLineParser.h (original)
+++ cfe/trunk/lib/Format/UnwrappedLineParser.h Tue Jul  9 04:06:29 2013
@@ -102,13 +102,6 @@ private:
   void calculateBraceTypes();
   void pushPPConditional();
 
-  // Represents what type of block a left brace opens.
-  enum LBraceState {
-    BS_Unknown,
-    BS_Block,
-    BS_BracedInit
-  };
-
   // FIXME: We are constantly running into bugs where Line.Level is incorrectly
   // subtracted from beyond 0. Introduce a method to subtract from Line.Level
   // and use that everywhere in the Parser.
@@ -153,11 +146,6 @@ private:
   // owned outside of and handed into the UnwrappedLineParser.
   ArrayRef<FormatToken *> AllTokens;
 
-  // FIXME: Currently we cannot store attributes with tokens, as we treat
-  // them as read-only; thus, we now store the brace state indexed by the
-  // position of the token in the stream (see \c AllTokens).
-  SmallVector<LBraceState, 16> LBraces;
-
   // Represents preprocessor branch type, so we can find matching
   // #if/#else/#endif directives.
   enum PPBranchKind {

Modified: cfe/trunk/unittests/Format/FormatTest.cpp
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTest.cpp?rev=185914&r1=185913&r2=185914&view=diff
==============================================================================
--- cfe/trunk/unittests/Format/FormatTest.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTest.cpp Tue Jul  9 04:06:29 2013
@@ -3785,6 +3785,13 @@ TEST_F(FormatTest, LayoutCxx11Constructo
         "                                 bbbbbbbbbbbbbbbbbbbb, bbbbb };");
     verifyFormat("DoSomethingWithVector({} /* No data */);");
     verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });");
+    verifyFormat(
+        "someFunction(OtherParam, BracedList{\n"
+        "                           // comment 1 (Forcing intersting break)\n"
+        "                           param1, param2,\n"
+        "                           // comment 2\n"
+        "                           param3, param4\n"
+        "                         });");
 
     FormatStyle NoSpaces = getLLVMStyle();
     NoSpaces.SpacesInBracedLists = false;





More information about the cfe-commits mailing list