[clang] [clang-format] Don't annotate arrow after a binary operator as trailing return (PR #241555)
via cfe-commits
cfe-commits at lists.llvm.org
Mon Nov 23 16:50:54 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;
----------------
ljkx wrote:
That's fair, and I agree it's tightly fitted. I checked the comment you linked against the issue's example: with `StatementAttributeLikeMacros: [DO_DEBUG]`, clang-format 23.1.6 already formats `DO_DEBUG debug() << foo->bar();` correctly, without this patch. There's also already a test for that (`emit foo()->bar;` with `emit` in the option). The `auto(x)->y` case from the other thread is another sign that a heuristic here only covers part of the problem.
So the option is the right fix for the reporter, and this patch doesn't add much on top of it. If you agree, I'll close the PR, and maybe the issue can be closed pointing at `StatementAttributeLikeMacros`. Sorry for taking up your review time on it.
https://github.com/llvm/llvm-project/pull/241555
More information about the cfe-commits
mailing list