[clang] clang-format: ensure ternary operands are aligned (PR #196697)
Eugene Shalygin via cfe-commits
cfe-commits at lists.llvm.org
Sat May 9 06:03:18 PDT 2026
https://github.com/zeule updated https://github.com/llvm/llvm-project/pull/196697
>From a0d72baa701df3dee6364bd3948b8d9877d1bd24 Mon Sep 17 00:00:00 2001
From: Eugene Shalygin <eugene.shalygin at gmail.com>
Date: Sat, 9 May 2026 09:06:41 +0200
Subject: [PATCH] clang-format: ensure ternary operands are aligned
Set ParentState::AlignedTo for ternary operands.
---
clang/lib/Format/ContinuationIndenter.cpp | 15 +++++++++++++++
clang/unittests/Format/AlignmentTest.cpp | 10 ++++++++++
2 files changed, 25 insertions(+)
diff --git a/clang/lib/Format/ContinuationIndenter.cpp b/clang/lib/Format/ContinuationIndenter.cpp
index b2f799bb33b01..5cd771cacc193 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -1276,6 +1276,21 @@ unsigned ContinuationIndenter::addTokenOnNewLine(LineState &State,
CurrentState.BreakBeforeParameter = false;
CurrentState.AlignedTo = &Current;
}
+ if (!CurrentState.AlignedTo && Current.is(TT_ConditionalExpr)) {
+ switch (Style.AlignOperands) {
+ case FormatStyle::OAS_DontAlign:
+ break;
+ case FormatStyle::OAS_Align:
+ CurrentState.AlignedTo = Current.is(tok::question)
+ ? Current.getPrevious(tok::equal)
+ : Current.getPrevious(tok::question);
+ break;
+ case FormatStyle::OAS_AlignAfterOperator:
+ if (Current.is(tok::colon))
+ CurrentState.AlignedTo = Current.getPrevious(tok::question);
+ break;
+ }
+ }
if (!DryRun) {
unsigned MaxEmptyLinesToKeep = Style.MaxEmptyLinesToKeep + 1;
diff --git a/clang/unittests/Format/AlignmentTest.cpp b/clang/unittests/Format/AlignmentTest.cpp
index 971ceeefef582..9421a4c933b9e 100644
--- a/clang/unittests/Format/AlignmentTest.cpp
+++ b/clang/unittests/Format/AlignmentTest.cpp
@@ -3599,6 +3599,16 @@ TEST_F(AlignmentTest, ContinuedAligned) {
"\t},\n"
"\tvariant);",
Style);
+
+ Style.ColumnLimit = 40;
+ Style.IndentWidth = Style.TabWidth = Style.ContinuationIndentWidth = 8;
+
+ verifyFormat("void f() {\n"
+ "\tint aaaaaaaaaaaaaaaaaaaa =\n"
+ "\t\t000000000000000001 ? 2\n"
+ "\t\t : 3;\n"
+ "}",
+ Style);
}
} // namespace
More information about the cfe-commits
mailing list