[clang] bb4f6c4 - [clang-format] Treat NTTP default values as expressions

Emilia Dreamer via cfe-commits cfe-commits at lists.llvm.org
Sat Mar 25 18:42:48 PDT 2023


Author: Emilia Dreamer
Date: 2023-03-26T04:39:10+03:00
New Revision: bb4f6c4dca98a47054117708015bb2724256ee83

URL: https://github.com/llvm/llvm-project/commit/bb4f6c4dca98a47054117708015bb2724256ee83
DIFF: https://github.com/llvm/llvm-project/commit/bb4f6c4dca98a47054117708015bb2724256ee83.diff

LOG: [clang-format] Treat NTTP default values as expressions

clang-format already has logic to threat the right-hand side of an
equals sign. This patch applies that logic to template defaults,
which are likely to be non-template type parameters in which case the
default value should be annotated as an expression.
This should mostly only ever apply to bool and &&.

Fixes https://github.com/llvm/llvm-project/issues/61664

Reviewed By: MyDeveloperDay, owenpan

Differential Revision: https://reviews.llvm.org/D146760

Added: 
    

Modified: 
    clang/lib/Format/TokenAnnotator.cpp
    clang/unittests/Format/TokenAnnotatorTest.cpp

Removed: 
    


################################################################################
diff  --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp
index dfde6e4e0163..91f9d5719b5a 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1722,6 +1722,11 @@ class AnnotatingParser {
           return false;
         }
 
+        // This is the default value of a non-template type parameter, so treat
+        // it as an expression.
+        if (Contexts.back().ContextKind == tok::less)
+          return true;
+
         Tok = Tok->MatchingParen;
         if (!Tok)
           return false;

diff  --git a/clang/unittests/Format/TokenAnnotatorTest.cpp b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 997630d08e2e..94b3a77ed5a0 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -253,6 +253,14 @@ TEST_F(TokenAnnotatorTest, UnderstandsUsesOfStarAndAmp) {
                     "};");
   ASSERT_EQ(Tokens.size(), 30u) << Tokens;
   EXPECT_TOKEN(Tokens[14], tok::ampamp, TT_BinaryOperator);
+
+  Tokens = annotate("template <bool B = C && D> struct S {};");
+  ASSERT_EQ(Tokens.size(), 15u) << Tokens;
+  EXPECT_TOKEN(Tokens[6], tok::ampamp, TT_BinaryOperator);
+
+  Tokens = annotate("template <typename T, bool B = C && D> struct S {};");
+  ASSERT_EQ(Tokens.size(), 18u) << Tokens;
+  EXPECT_TOKEN(Tokens[9], tok::ampamp, TT_BinaryOperator);
 }
 
 TEST_F(TokenAnnotatorTest, UnderstandsUsesOfPlusAndMinus) {


        


More information about the cfe-commits mailing list