[clang] [clang-format] Don't annotate arrow after a binary operator as trailing return (PR #241555)

Björn Schäpers via cfe-commits cfe-commits at lists.llvm.org
Mon Nov 23 14:00:45 PST 2026


================
@@ -4226,9 +4226,42 @@ void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) const {
         }
       }
     } else if (ClosingParen) {
+      const auto ParamListLevel = ClosingParen->MatchingParen->NestingLevel;
+      bool InExpression = false;
       for (auto *Tok = ClosingParen->Next; Tok; Tok = Tok->Next) {
         if (Tok->is(TT_CtorInitializerColon))
           break;
+        // A binary operator at the level of the parameter list, e.g. `<<` in
+        // `MACRO foo() << a->b;`, means that the rest of the line is an
+        // expression rather than the trailer of a function declaration. `&`
+        // and `&&` are exempt as a ref-qualifier may be annotated as a binary
+        // operator, e.g. in `auto f() const & NOEXCEPT -> int;`.
+        if (Tok->is(TT_BinaryOperator) &&
+            Tok->isNoneOf(tok::amp, tok::ampamp) &&
+            Tok->NestingLevel == ParamListLevel) {
+          InExpression = true;
+          continue;
+        }
+        if (InExpression) {
+          // In an expression, only a function type spelled with `auto` can
+          // have a trailing return arrow, e.g. the cast in
+          // `MACRO foo() << (auto (*)() -> int)(a);`.
+          if (Tok->isNot(tok::kw_auto) || Tok->NestingLevel == ParamListLevel)
+            continue;
+          // Skip the optional parenthesized declarator and the parameter list.
+          auto *Next = Tok->Next;
+          for (int I = 0; I < 2; ++I) {
+            if (!Next || Next->isNot(tok::l_paren) || !Next->MatchingParen)
+              break;
+            Next = Next->MatchingParen->Next;
+          }
+          if (Next && Next->is(tok::arrow) &&
+              Next->Previous->is(tok::r_paren)) {
+            Next->overwriteFixedType(TT_TrailingReturnArrow);
+            break;
----------------
HazardyKnusperkeks wrote:

Now I just add comments.

This seems a bit to tightly fit. And given https://github.com/llvm/llvm-project/issues/225672#issuecomment-7022556879 I question if it is really worth spending time on it. We have the `StatementAttributeLikeMacros` exactly for this.

https://github.com/llvm/llvm-project/pull/241555


More information about the cfe-commits mailing list