[clang-format] Reimplement InsertNewlineAtEOF (#108513)
authorOwen Pan <owenpiano@gmail.com>
Wed, 18 Sep 2024 04:16:20 +0000 (21:16 -0700)
committerTobias Hieta <tobias@hieta.se>
Tue, 24 Sep 2024 06:31:46 +0000 (08:31 +0200)
Fixes #108333.

(cherry picked from commit 7153a4bbf6d46e58ce32d59220515c5ab9f35691)

clang/lib/Format/FormatTokenLexer.cpp
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/FormatTest.cpp

index e21b5a882b7773eed9d4b030540a47873051fc7e..63949b2e26bdc16a56c22fe38e2add6481121e7f 100644 (file)
@@ -100,6 +100,13 @@ ArrayRef<FormatToken *> FormatTokenLexer::lex() {
     if (Tokens.back()->NewlinesBefore > 0 || Tokens.back()->IsMultiline)
       FirstInLineIndex = Tokens.size() - 1;
   } while (Tokens.back()->isNot(tok::eof));
+  if (Style.InsertNewlineAtEOF) {
+    auto &TokEOF = *Tokens.back();
+    if (TokEOF.NewlinesBefore == 0) {
+      TokEOF.NewlinesBefore = 1;
+      TokEOF.OriginalColumn = 0;
+    }
+  }
   return Tokens;
 }
 
index 3f00a28e62988a073a572e3fa9b199d17ccf728c..4512e539cc7947d49a690960c53001cc18af1ec7 100644 (file)
@@ -3680,11 +3680,6 @@ void TokenAnnotator::annotate(AnnotatedLine &Line) {
   auto *First = Line.First;
   First->SpacesRequiredBefore = 1;
   First->CanBreakBefore = First->MustBreakBefore;
-
-  if (First->is(tok::eof) && First->NewlinesBefore == 0 &&
-      Style.InsertNewlineAtEOF) {
-    First->NewlinesBefore = 1;
-  }
 }
 
 // This function heuristically determines whether 'Current' starts the name of a
index 29200b72d3d0083e26e4b18020d61d68cbe54635..b7d8fc8ea72c6cc20f9157ccd3705e740aa7fa43 100644 (file)
@@ -27364,6 +27364,12 @@ TEST_F(FormatTest, InsertNewlineAtEOF) {
 
   verifyNoChange("int i;\n", Style);
   verifyFormat("int i;\n", "int i;", Style);
+
+  constexpr StringRef Code{"namespace {\n"
+                           "int i;\n"
+                           "} // namespace"};
+  verifyFormat(Code.str() + '\n', Code, Style,
+               {tooling::Range(19, 13)}); // line 3
 }
 
 TEST_F(FormatTest, KeepEmptyLinesAtEOF) {