[clang] [clang-format][NFC] Refactor getting first/last non-comment of line (PR #74570)

Owen Pan via cfe-commits cfe-commits at lists.llvm.org
Tue Dec 5 23:35:41 PST 2023


https://github.com/owenca created https://github.com/llvm/llvm-project/pull/74570

None

>From a37925ae51d95e91d32ec50bc39a9b6e5b13c571 Mon Sep 17 00:00:00 2001
From: Owen Pan <owenpiano at gmail.com>
Date: Tue, 5 Dec 2023 23:31:28 -0800
Subject: [PATCH] [clang-format][NFC] Refactor getting first/last non-comment
 of line

---
 clang/lib/Format/TokenAnnotator.h           |  5 +++++
 clang/lib/Format/UnwrappedLineFormatter.cpp | 19 ++++++-------------
 2 files changed, 11 insertions(+), 13 deletions(-)

diff --git a/clang/lib/Format/TokenAnnotator.h b/clang/lib/Format/TokenAnnotator.h
index 58e2cf79f488f..05a6daa87d803 100644
--- a/clang/lib/Format/TokenAnnotator.h
+++ b/clang/lib/Format/TokenAnnotator.h
@@ -156,6 +156,11 @@ class AnnotatedLine {
     return First->is(tok::comment) ? First->getNextNonComment() : First;
   }
 
+  FormatToken *getLastNonComment() const {
+    assert(Last);
+    return Last->is(tok::comment) ? Last->getPreviousNonComment() : Last;
+  }
+
   FormatToken *First;
   FormatToken *Last;
 
diff --git a/clang/lib/Format/UnwrappedLineFormatter.cpp b/clang/lib/Format/UnwrappedLineFormatter.cpp
index 40730cd53529e..b4930c2e4621d 100644
--- a/clang/lib/Format/UnwrappedLineFormatter.cpp
+++ b/clang/lib/Format/UnwrappedLineFormatter.cpp
@@ -346,14 +346,10 @@ class LineJoiner {
             return false;
 
           // Check if the found line starts a record.
-          const FormatToken *LastNonComment = Line->Last;
+          const auto *LastNonComment = Line->getLastNonComment();
+          // There must be another token (usually `{`), because we chose a
+          // non-PPDirective and non-comment line that has a smaller level.
           assert(LastNonComment);
-          if (LastNonComment->is(tok::comment)) {
-            LastNonComment = LastNonComment->getPreviousNonComment();
-            // There must be another token (usually `{`), because we chose a
-            // non-PPDirective and non-comment line that has a smaller level.
-            assert(LastNonComment);
-          }
           return isRecordLBrace(*LastNonComment);
         }
       }
@@ -363,12 +359,9 @@ class LineJoiner {
 
     bool MergeShortFunctions = ShouldMergeShortFunctions();
 
-    const FormatToken *FirstNonComment = TheLine->First;
-    if (FirstNonComment->is(tok::comment)) {
-      FirstNonComment = FirstNonComment->getNextNonComment();
-      if (!FirstNonComment)
-        return 0;
-    }
+    const auto *FirstNonComment = TheLine->getFirstNonComment();
+    if (!FirstNonComment)
+      return 0;
     // FIXME: There are probably cases where we should use FirstNonComment
     // instead of TheLine->First.
 



More information about the cfe-commits mailing list