[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:51 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)
----------------
ljkx wrote:
Added one in add55fe8: `DO_DEBUG debug() << (foo()->bar);`. The arrow follows a nested `foo()` that isn't `auto`, and it's now checked to stay `TT_Unknown`. If I drop the `kw_auto` check, the test fails.
To be thorough I also tried `auto` at the parameter list's level, `DO_DEBUG debug() << auto(x)->y;`. It is still formatted as `auto(x) -> y`. That doesn't come from this loop: the line has `auto` at nesting level 0, so `determineTokenType` already annotates the arrow. I haven't added a test for it.
https://github.com/llvm/llvm-project/pull/241555
More information about the cfe-commits
mailing list