From: Daniel Jasper Date: Fri, 31 May 2013 14:56:12 +0000 (+0000) Subject: Properly format nested conditional operators. X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=c01897c3f6139304ed25e3f673bef77be209617f;p=clang Properly format nested conditional operators. Before: bool aaaaaa = aaaaaaaaaaaaa // ? aaaaaaaaaaaaaaa : bbbbbbbbbbbbbbb // ? ccccccccccccccc : ddddddddddddddd; After: bool aaaaaa = aaaaaaaaaaaaa // ? aaaaaaaaaaaaaaa : bbbbbbbbbbbbbbb // ? ccccccccccccccc : ddddddddddddddd; git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@183007 91177308-0d34-0410-b5e6-96231b3b80d8 --- diff --git a/lib/Format/TokenAnnotator.cpp b/lib/Format/TokenAnnotator.cpp index 9a1a2ab44b..3e89f79444 100644 --- a/lib/Format/TokenAnnotator.cpp +++ b/lib/Format/TokenAnnotator.cpp @@ -757,6 +757,11 @@ public: /// \brief Parse expressions with the given operatore precedence. void parse(int Precedence = 0) { + // Conditional expressions need to be parsed separately for proper nesting. + if (Precedence == prec::Conditional + 1) { + parseConditionalExpr(); + return; + } if (Precedence > prec::PointerToMember || Current == NULL) return; @@ -786,11 +791,8 @@ public: // found, insert fake parenthesis and return. if (Current == NULL || Current->closesScope() || (CurrentPrecedence != 0 && CurrentPrecedence < Precedence)) { - if (OperatorFound) { - Start->FakeLParens.push_back(prec::Level(Precedence - 1)); - if (Current) - ++Current->Previous->FakeRParens; - } + if (OperatorFound) + addFakeParenthesis(Start, prec::Level(Precedence - 1)); return; } @@ -812,6 +814,26 @@ public: } private: + void addFakeParenthesis(FormatToken *Start, prec::Level Precedence) { + Start->FakeLParens.push_back(Precedence); + if (Current) + ++Current->Previous->FakeRParens; + } + + void parseConditionalExpr() { + FormatToken *Start = Current; + parse(prec::LogicalOr + 1); + if (!Current || !Current->is(tok::question)) + return; + next(); + parse(prec::LogicalOr + 1); + if (!Current || Current->Type != TT_ConditionalExpr) + return; + next(); + parseConditionalExpr(); + addFakeParenthesis(Start, prec::Conditional); + } + void next() { if (Current != NULL) Current = Current->Next; diff --git a/unittests/Format/FormatTest.cpp b/unittests/Format/FormatTest.cpp index 8b306f240c..b09daa867b 100644 --- a/unittests/Format/FormatTest.cpp +++ b/unittests/Format/FormatTest.cpp @@ -2551,6 +2551,16 @@ TEST_F(FormatTest, BreaksConditionalExpressions) { " : TheLine * 2,\n" " TheLine.InPPDirective, PreviousEndOfLineColumn);", getLLVMStyleWithColumns(70)); + verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n" + " ? aaaaaaaaaaaaaaa\n" + " : bbbbbbbbbbbbbbb //\n" + " ? ccccccccccccccc\n" + " : ddddddddddddddd;"); + verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n" + " ? aaaaaaaaaaaaaaa\n" + " : (bbbbbbbbbbbbbbb //\n" + " ? ccccccccccccccc\n" + " : ddddddddddddddd);"); FormatStyle NoBinPacking = getLLVMStyle(); NoBinPacking.BinPackParameters = false;