[PATCH] Even better way to handle comments adjacent to preprocessor directives.

Alexander Kornienko alexfh at google.com
Wed Apr 3 05:23:53 PDT 2013


Hi klimek,

It turns out that we don't need to store CommentsBeforeNextToken in the
line state, but rather flush them before we start parsing preprocessor
directives. This fixes wrong comment indentation in code blocks in macro calls
(the test is included).

http://llvm-reviews.chandlerc.com/D617

Files:
  lib/Format/UnwrappedLineParser.cpp
  unittests/Format/FormatTest.cpp

Index: lib/Format/UnwrappedLineParser.cpp
===================================================================
--- lib/Format/UnwrappedLineParser.cpp
+++ lib/Format/UnwrappedLineParser.cpp
@@ -100,7 +100,6 @@
     Parser.Line.reset(new UnwrappedLine());
     Parser.Line->Level = PreBlockLine->Level;
     Parser.Line->InPPDirective = PreBlockLine->InPPDirective;
-    Parser.CommentsBeforeNextToken.swap(CommentsBeforeNextToken);
   }
 
   ~ScopedLineState() {
@@ -112,15 +111,13 @@
     Parser.MustBreakBeforeNextToken = true;
     if (SwitchToPreprocessorLines)
       Parser.CurrentLines = &Parser.Lines;
-    Parser.CommentsBeforeNextToken.swap(CommentsBeforeNextToken);
   }
 
 private:
   UnwrappedLineParser &Parser;
   const bool SwitchToPreprocessorLines;
 
   UnwrappedLine *PreBlockLine;
-  SmallVector<FormatToken, 1> CommentsBeforeNextToken;
 };
 
 UnwrappedLineParser::UnwrappedLineParser(
@@ -830,6 +827,10 @@
       bool SwitchToPreprocessorLines =
           !Line->Tokens.empty() && CurrentLines == &Lines;
       ScopedLineState BlockState(*this, SwitchToPreprocessorLines);
+      // Comments before the preprocessor directive should be flushed before we
+      // start parsing the directive so that they are not treated as a part of
+      // it.
+      flushComments(FormatTok.NewlinesBefore > 0);
       parsePPDirective();
     }
     if (!FormatTok.Tok.is(tok::comment))
Index: unittests/Format/FormatTest.cpp
===================================================================
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -592,6 +592,14 @@
   verifyGoogleFormat(
       "aaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
       "    aaaaaaaaaaaaaaaaaaaaaa);  // 81 cols with this comment");
+  EXPECT_EQ("D(a, {\n"
+            "  // test\n"
+            "  int a;\n"
+            "});",
+            format("D(a, {\n"
+                   "// test\n"
+                   "int a;\n"
+                   "});"));
 }
 
 TEST_F(FormatTest, CanFormatCommentsLocally) {
-------------- next part --------------
A non-text attachment was scrubbed...
Name: D617.1.patch
Type: text/x-patch
Size: 2002 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20130403/a5fb9235/attachment.bin>


More information about the cfe-commits mailing list