Skip to content

[clang-format] Add BreakBeforeTemplateCloser option #118046

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 34 commits into from
Feb 6, 2025

Conversation

leijurv
Copy link
Contributor

@leijurv leijurv commented Nov 29, 2024

In clang-format, multiline templates have the > on the same line as the last parameter:

template <
    typename Foo,
    typename Bar>
void foo() {

I would like to add an option to put the > on the next line, like this:

template <
    typename Foo,
    typename Bar
>
void foo() {

An example of a large project that uses this style is NVIDIA's CUTLASS, here is an example:

https://github.com/NVIDIA/cutlass/blob/main/include/cutlass/epilogue/dispatch_policy.hpp#L149-L156

My reasoning is that it reminds me of this style of braces:

if (foo()) {
    bar();
    baz();}

Most people agree this is better:

if (foo()) {
    bar();
    baz();
}

Copy link

Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this page.

If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using @ followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers.

If you have further questions, they may be answered by the LLVM GitHub User Guide.

You can also ask questions in a comment on this PR, on the LLVM Discord or on the forums.

@leijurv leijurv force-pushed the BreakBeforeTemplateClose branch from 3594846 to de78cfb Compare November 30, 2024 03:35
@leijurv leijurv changed the title BreakBeforeTemplateClose [clang-format] Add BreakBeforeTemplateClose option Nov 30, 2024
@leijurv leijurv force-pushed the BreakBeforeTemplateClose branch from a742812 to 217f807 Compare November 30, 2024 03:55
@leijurv leijurv marked this pull request as ready for review November 30, 2024 03:55
@llvmbot llvmbot added clang Clang issues not falling into any other category clang-format labels Nov 30, 2024
@llvmbot
Copy link
Member

llvmbot commented Nov 30, 2024

@llvm/pr-subscribers-clang

@llvm/pr-subscribers-clang-format

Author: leijurv (leijurv)

Changes

In clang-format, multiline templates have the &gt; on the same line as the last parameter:

template&lt;
    typename Foo,
    typename Bar,
    typename Baz&gt;
void foo() {

I would like to add an option to put the &gt; on the next line, like this:

template&lt;
    typename Foo,
    typename Bar,
    typename Baz
&gt;
void foo() {

My reasoning is that it reminds me of this style of braces:

if (foo()) {
    bar();}

Most people agree this is better:

if (foo()) {
    bar();
}

Full diff: https://github.com/llvm/llvm-project/pull/118046.diff

7 Files Affected:

  • (modified) clang/docs/ClangFormatStyleOptions.rst (+23)
  • (modified) clang/docs/ReleaseNotes.rst (+1)
  • (modified) clang/include/clang/Format/Format.h (+20)
  • (modified) clang/lib/Format/ContinuationIndenter.cpp (+18)
  • (modified) clang/lib/Format/Format.cpp (+2)
  • (modified) clang/unittests/Format/ConfigParseTest.cpp (+1)
  • (modified) clang/unittests/Format/FormatTest.cpp (+79)
diff --git a/clang/docs/ClangFormatStyleOptions.rst b/clang/docs/ClangFormatStyleOptions.rst
index 4be448171699ca..31ed9a10d7153d 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -3416,6 +3416,29 @@ the configuration (without a prefix: ``Auto``).
 
 
 
+
+.. _BreakBeforeTemplateClose:
+
+**BreakBeforeTemplateClose** (``Boolean``) :versionbadge:`clang-format 20` :ref:`¶ <BreakBeforeTemplateClose>`
+  If ``true``, a line break will be placed before the ``>`` in a multiline template declaration.
+
+  .. code-block:: c++
+
+     true:
+     template <
+         typename Foo,
+         typename Bar,
+         typename Baz
+     >
+
+     false:
+     template <
+         typename Foo,
+         typename Bar,
+         typename Baz>
+
+
+
 .. _BreakBeforeTernaryOperators:
 
 **BreakBeforeTernaryOperators** (``Boolean``) :versionbadge:`clang-format 3.7` :ref:`¶ <BreakBeforeTernaryOperators>`
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index e44aefa90ab386..867d4b5d8c3f18 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -976,6 +976,7 @@ clang-format
   ``Never``, and ``true`` to ``Always``.
 - Adds ``RemoveEmptyLinesInUnwrappedLines`` option.
 - Adds ``KeepFormFeed`` option and set it to ``true`` for ``GNU`` style.
+- Adds ``BreakBeforeTemplateClose`` option.
 
 libclang
 --------
diff --git a/clang/include/clang/Format/Format.h b/clang/include/clang/Format/Format.h
index 6383934afa2c40..bffd964f6aa8aa 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -2248,6 +2248,25 @@ struct FormatStyle {
   /// \version 16
   BreakBeforeInlineASMColonStyle BreakBeforeInlineASMColon;
 
+  /// If ``true``, a line break will be placed before the ``>`` in a multiline
+  /// template declaration.
+  /// \code
+  ///    true:
+  ///    template <
+  ///        typename Foo,
+  ///        typename Bar,
+  ///        typename Baz
+  ///    >
+  ///
+  ///    false:
+  ///    template <
+  ///        typename Foo,
+  ///        typename Bar,
+  ///        typename Baz>
+  /// \endcode
+  /// \version 20
+  bool BreakBeforeTemplateClose;
+
   /// If ``true``, ternary operators will be placed after line breaks.
   /// \code
   ///    true:
@@ -5184,6 +5203,7 @@ struct FormatStyle {
            BreakBeforeBraces == R.BreakBeforeBraces &&
            BreakBeforeConceptDeclarations == R.BreakBeforeConceptDeclarations &&
            BreakBeforeInlineASMColon == R.BreakBeforeInlineASMColon &&
+           BreakBeforeTemplateClose == R.BreakBeforeTemplateClose &&
            BreakBeforeTernaryOperators == R.BreakBeforeTernaryOperators &&
            BreakBinaryOperations == R.BreakBinaryOperations &&
            BreakConstructorInitializers == R.BreakConstructorInitializers &&
diff --git a/clang/lib/Format/ContinuationIndenter.cpp b/clang/lib/Format/ContinuationIndenter.cpp
index aed86c1fb99551..0c77c18b3e7f48 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -382,10 +382,25 @@ bool ContinuationIndenter::canBreak(const LineState &State) {
   return !State.NoLineBreak && !CurrentState.NoLineBreak;
 }
 
+bool isMatchingBraceOnSameLine(const FormatToken *Token) {
+  if (!Token->MatchingParen)
+    return false;
+  const FormatToken *Matching = Token->MatchingParen;
+  const FormatToken *Current = Token;
+  while (Current && Current != Matching) {
+    if (Current->NewlinesBefore > 0)
+      return false;
+    Current = Current->Previous;
+  }
+  return true;
+}
+
 bool ContinuationIndenter::mustBreak(const LineState &State) {
   const FormatToken &Current = *State.NextToken;
   const FormatToken &Previous = *Current.Previous;
   const auto &CurrentState = State.Stack.back();
+  if (Current.ClosesTemplateDeclaration && Style.BreakBeforeTemplateClose)
+    return !isMatchingBraceOnSameLine(State.NextToken);
   if (Style.BraceWrapping.BeforeLambdaBody && Current.CanBreakBefore &&
       Current.is(TT_LambdaLBrace) && Previous.isNot(TT_LineComment)) {
     auto LambdaBodyLength = getLengthToMatchingParen(Current, State.Stack);
@@ -1279,6 +1294,9 @@ unsigned ContinuationIndenter::getNewLineColumn(const LineState &State) {
   FormatToken &Current = *State.NextToken;
   const auto &CurrentState = State.Stack.back();
 
+  if (Current.ClosesTemplateDeclaration && Style.BreakBeforeTemplateClose)
+    return CurrentState.Indent - Style.ContinuationIndentWidth;
+
   if (CurrentState.IsCSharpGenericTypeConstraint &&
       Current.isNot(TT_CSharpGenericTypeConstraint)) {
     return CurrentState.ColonPos + 2;
diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index ee52972ce66f4a..d6aa80dd8e3aef 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -1000,6 +1000,7 @@ template <> struct MappingTraits<FormatStyle> {
     IO.mapOptional("BreakBeforeBraces", Style.BreakBeforeBraces);
     IO.mapOptional("BreakBeforeInlineASMColon",
                    Style.BreakBeforeInlineASMColon);
+    IO.mapOptional("BreakBeforeTemplateClose", Style.BreakBeforeTemplateClose);
     IO.mapOptional("BreakBeforeTernaryOperators",
                    Style.BreakBeforeTernaryOperators);
     IO.mapOptional("BreakBinaryOperations", Style.BreakBinaryOperations);
@@ -1514,6 +1515,7 @@ FormatStyle getLLVMStyle(FormatStyle::LanguageKind Language) {
   LLVMStyle.BreakBeforeBraces = FormatStyle::BS_Attach;
   LLVMStyle.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Always;
   LLVMStyle.BreakBeforeInlineASMColon = FormatStyle::BBIAS_OnlyMultiline;
+  LLVMStyle.BreakBeforeTemplateClose = false;
   LLVMStyle.BreakBeforeTernaryOperators = true;
   LLVMStyle.BreakBinaryOperations = FormatStyle::BBO_Never;
   LLVMStyle.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
diff --git a/clang/unittests/Format/ConfigParseTest.cpp b/clang/unittests/Format/ConfigParseTest.cpp
index 7fc7492271668b..39f4ea49719600 100644
--- a/clang/unittests/Format/ConfigParseTest.cpp
+++ b/clang/unittests/Format/ConfigParseTest.cpp
@@ -162,6 +162,7 @@ TEST(ConfigParseTest, ParsesConfigurationBools) {
   CHECK_PARSE_BOOL(BinPackArguments);
   CHECK_PARSE_BOOL(BreakAdjacentStringLiterals);
   CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations);
+  CHECK_PARSE_BOOL(BreakBeforeTemplateClose);
   CHECK_PARSE_BOOL(BreakBeforeTernaryOperators);
   CHECK_PARSE_BOOL(BreakStringLiterals);
   CHECK_PARSE_BOOL(CompactNamespaces);
diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp
index 250e51b5421664..1dffce7925a055 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -11077,6 +11077,85 @@ TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) {
       Style);
 }
 
+TEST_F(FormatTest, BreakBeforeTemplateClose) {
+  FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
+  Style.BreakTemplateDeclarations = FormatStyle::BTDS_Yes;
+  Style.ColumnLimit = 0;
+  verifyNoChange("template <typename Foo>\n"
+                 "void foo() {}",
+                 Style);
+  verifyNoChange("template <\n"
+                 "    typename Foo,\n"
+                 "    typename Bar>\n"
+                 "void foo() {}",
+                 Style);
+  // when BreakBeforeTemplateClose is off, this line break is removed:
+  verifyFormat("template <\n"
+               "    typename Foo,\n"
+               "    typename Bar>\n"
+               "void foo() {}",
+               "template <\n"
+               "    typename Foo,\n"
+               "    typename Bar\n"
+               ">\n"
+               "void foo() {}",
+               Style);
+  Style.BreakBeforeTemplateClose = true;
+  // BreakBeforeTemplateClose should NOT force multiline templates
+  verifyNoChange("template <typename Foo>\n"
+                 "void foo() {}",
+                 Style);
+  verifyNoChange("template <typename Foo, typename Bar>\n"
+                 "void foo() {}",
+                 Style);
+  // it should allow a line break:
+  verifyNoChange("template <\n"
+                 "    typename Foo\n"
+                 ">\n"
+                 "void foo() {}",
+                 Style);
+  verifyNoChange("template <\n"
+                 "    typename Foo,\n"
+                 "    typename Bar\n"
+                 ">\n"
+                 "void foo() {}",
+                 Style);
+  // it should add a line break if not already present:
+  verifyFormat("template <\n"
+               "    typename Foo\n"
+               ">\n"
+               "void foo() {}",
+               "template <\n"
+               "    typename Foo>\n"
+               "void foo() {}",
+               Style);
+  verifyFormat("template <\n"
+               "    typename Foo,\n"
+               "    typename Bar\n"
+               ">\n"
+               "void foo() {}",
+               "template <\n"
+               "    typename Foo,\n"
+               "    typename Bar>\n"
+               "void foo() {}",
+               Style);
+  // when within an indent scope, the > should be placed appropriately:
+  verifyFormat("struct Baz {\n"
+               "  template <\n"
+               "      typename Foo,\n"
+               "      typename Bar\n"
+               "  >\n"
+               "  void foo() {}\n"
+               "};",
+               "struct Baz {\n"
+               "  template <\n"
+               "      typename Foo,\n"
+               "      typename Bar>\n"
+               "  void foo() {}\n"
+               "};",
+               Style);
+}
+
 TEST_F(FormatTest, WrapsTemplateParameters) {
   FormatStyle Style = getLLVMStyle();
   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;

@leijurv leijurv force-pushed the BreakBeforeTemplateClose branch 4 times, most recently from efb5b98 to b254c93 Compare November 30, 2024 21:12
@leijurv leijurv force-pushed the BreakBeforeTemplateClose branch from b254c93 to 1caf823 Compare November 30, 2024 21:24
@leijurv
Copy link
Contributor Author

leijurv commented Dec 7, 2024

Ping 🙏

@gedare
Copy link
Contributor

gedare commented Dec 7, 2024

Would this also be equivalent to supporting AlignAfterOpenBracket: BlockIndent for angle brackets?

@leijurv
Copy link
Contributor Author

leijurv commented Dec 7, 2024

Yes. I followed the code that implements AlignAfterOpenBracket: BlockIndent, except applying to ClosesTemplateDeclaration. I made it a new setting for backwards compatibility. 👍

@gedare
Copy link
Contributor

gedare commented Dec 7, 2024

Yes. I followed the code that implements AlignAfterOpenBracket: BlockIndent, except applying to ClosesTemplateDeclaration. I made it a new setting for backwards compatibility. 👍

Maybe we should make it a sub-option for BlockIndent. I'm seeing a possible need for having control over other kinds of block indented structures such as Lambdas. I suspect the way this option has been implemented it interacts with the alignment options anyway. This would be a question probably for @owenca

@gedare
Copy link
Contributor

gedare commented Dec 7, 2024

Yes. I followed the code that implements AlignAfterOpenBracket: BlockIndent, except applying to ClosesTemplateDeclaration. I made it a new setting for backwards compatibility. 👍

Maybe we should make it a sub-option for BlockIndent. I'm seeing a possible need for having control over other kinds of block indented structures such as Lambdas. I suspect the way this option has been implemented it interacts with the alignment options anyway. This would be a question probably for @owenca

I thought about it some more and I don't think it would be a good idea. Having a separate option seems a bit easier to handle, and allows mixing and matching by users.

@gedare
Copy link
Contributor

gedare commented Dec 7, 2024

I think you should add test cases with multiple >> closing, see UnderstandsTemplateParameters for example.

Consider trying the code snippet mentioned in #80049 as well.

@leijurv
Copy link
Contributor Author

leijurv commented Dec 7, 2024

I think you should add test cases with multiple >> closing, see UnderstandsTemplateParameters for example.

Consider trying the code snippet mentioned in #80049 as well.

Thank you for the suggestion! I have integrated that test case. It indicated that I was being too narrow - ClosesTemplateDeclaration only applies before functions, but, as you demonstrate, there are several other cases where templates are closed, so I have switched to TT_TemplateCloser.

212e444

@leijurv
Copy link
Contributor Author

leijurv commented Dec 16, 2024

Ping 🙏

@leijurv
Copy link
Contributor Author

leijurv commented Feb 4, 2025

Thank you so much for taking the time to review the tests! I apologize for all the redundancies.

I believe I have addressed all of your comments here: leijurv@e1eaba9

@leijurv
Copy link
Contributor Author

leijurv commented Feb 5, 2025

GitHub is having issues it appears - the commit leijurv@e1eaba9 is certainly pushed, and I even tried pushing an empty commit on top to kick github into working, leijurv@7d456ca but still this PR is in a glitched state that doesn't show those commits...

Screen Shot 2025-02-04 at 7 35 58 PM

@leijurv
Copy link
Contributor Author

leijurv commented Feb 5, 2025

Ah, it resolved itself as of leijurv@b6219e2

@leijurv leijurv requested a review from owenca February 5, 2025 03:45
@leijurv leijurv requested a review from owenca February 6, 2025 00:41
@owenca owenca changed the title [clang-format] Add BreakBeforeTemplateClose option [clang-format] Add BreakBeforeTemplateCloser option Feb 6, 2025
@leijurv leijurv requested a review from owenca February 6, 2025 08:00
@owenca owenca removed the clang Clang issues not falling into any other category label Feb 6, 2025
@owenca owenca merged commit d2b45ce into llvm:main Feb 6, 2025
5 of 8 checks passed
Copy link

github-actions bot commented Feb 6, 2025

@leijurv Congratulations on having your first Pull Request (PR) merged into the LLVM Project!

Your changes will be combined with recent changes from other authors, then tested by our build bots. If there is a problem with a build, you may receive a report in an email or a comment on this PR.

Please check whether problems have been caused by your change specifically, as the builds can include changes from many authors. It is not uncommon for your change to be included in a build that fails due to someone else's changes, or infrastructure issues.

How to do this, and the rest of the post-merge process, is covered in detail here.

If your change does cause a problem, it may be reverted, or you can revert it yourself. This is a normal part of LLVM development. You can fix your changes and open a new PR to merge them again.

If you don't get any reports, no action is required from you. Your changes are working as expected, well done!

@lengye7
Copy link

lengye7 commented Feb 6, 2025

Can this option be used to format any template like std::remove_cv_t<add_common_cv_reference<std::common_type_t<std::decay_t, std::decay_t>,T0,T1>>;?

@leijurv
Copy link
Contributor Author

leijurv commented Feb 6, 2025

Can this option be used to format any template like std::remove_cv_t<add_common_cv_reference<std::common_type_t<std::decay_t, std::decay_t>,T0,T1>>;?

Yes! In fact, that exact case is tested.

d2b45ce#diff-3f6f57cda9809a57c5b79e22b4181b3f3aaac7216262d0ef44108f39b0443e9bR11276-R11290

  // Test from https://github.com/llvm/llvm-project/issues/80049:
  verifyFormat(
      "using type = std::remove_cv_t<\n"
      "    add_common_cv_reference<\n"
      "        std::common_type_t<std::decay_t<T0>, std::decay_t<T1>>,\n"
      "        T0,\n"
      "        T1\n"
      "    >\n"
      ">;",
      "using type = std::remove_cv_t<\n"
      "    add_common_cv_reference<\n"
      "        std::common_type_t<std::decay_t<T0>, std::decay_t<T1>>,\n"
      "        T0,\n"
      "        T1>>;",
      Style);

Icohedron pushed a commit to Icohedron/llvm-project that referenced this pull request Feb 11, 2025
In clang-format, multiline templates have the `>` on the same line as
the last parameter:

```c++
template <
    typename Foo,
    typename Bar>
void foo() {
```

I would like to add an option to put the `>` on the next line, like
this:

```c++
template <
    typename Foo,
    typename Bar
>
void foo() {
```

An example of a large project that uses this style is NVIDIA's CUTLASS,
here is an example:


https://github.com/NVIDIA/cutlass/blob/main/include/cutlass/epilogue/dispatch_policy.hpp#L149-L156

My reasoning is that it reminds me of this style of braces:

```c++
if (foo()) {
    bar();
    baz();}
```

Most people agree this is better:

```c++
if (foo()) {
    bar();
    baz();
}
```

---------

Co-authored-by: Owen Pan <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

7 participants