[llvm-branch-commits] [clang] release/19.x: [clang-format] Reimplement InsertNewlineAtEOF (#108513) (PR #109170)

via llvm-branch-commits llvm-branch-commits at lists.llvm.org
Wed Sep 18 10:29:08 PDT 2024


https://github.com/llvmbot created https://github.com/llvm/llvm-project/pull/109170

Backport 7153a4bbf6d46e58ce32d59220515c5ab9f35691

Requested by: @owenca

>From 2cc6c7bde964931be2c9a6691da944678bcb31a8 Mon Sep 17 00:00:00 2001
From: Owen Pan <owenpiano at gmail.com>
Date: Tue, 17 Sep 2024 21:16:20 -0700
Subject: [PATCH] [clang-format] Reimplement InsertNewlineAtEOF (#108513)

Fixes #108333.

(cherry picked from commit 7153a4bbf6d46e58ce32d59220515c5ab9f35691)
---
 clang/lib/Format/FormatTokenLexer.cpp | 7 +++++++
 clang/lib/Format/TokenAnnotator.cpp   | 5 -----
 clang/unittests/Format/FormatTest.cpp | 6 ++++++
 3 files changed, 13 insertions(+), 5 deletions(-)

diff --git a/clang/lib/Format/FormatTokenLexer.cpp b/clang/lib/Format/FormatTokenLexer.cpp
index e21b5a882b7773..63949b2e26bdc1 100644
--- a/clang/lib/Format/FormatTokenLexer.cpp
+++ b/clang/lib/Format/FormatTokenLexer.cpp
@@ -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;
 }
 
diff --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp
index 3f00a28e62988a..4512e539cc7947 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -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
diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp
index 29200b72d3d008..b7d8fc8ea72c6c 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -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) {



More information about the llvm-branch-commits mailing list