From: Daniel Jasper Date: Mon, 24 Dec 2012 00:13:23 +0000 (+0000) Subject: Take operator precedence into account when splitting lines. X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=e2c7acf58856fec94ed2b8089116e1ad80e3c30f;p=clang Take operator precedence into account when splitting lines. With this patch, splitting after binary operators has a panelty corresponding to the operator's precedence. We used to ignore this and eagerly format like: if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) { .. } With this patch, this becomes: if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) { .. } git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@171007 91177308-0d34-0410-b5e6-96231b3b80d8 --- diff --git a/lib/Format/Format.cpp b/lib/Format/Format.cpp index 2a8fbd6e5e..ad85a8ecf2 100644 --- a/lib/Format/Format.cpp +++ b/lib/Format/Format.cpp @@ -90,7 +90,7 @@ public: : Style(Style), SourceMgr(SourceMgr), Line(Line), Annotations(Annotations), Replaces(Replaces), StructuralError(StructuralError) { - Parameters.PenaltyIndentLevel = 5; + Parameters.PenaltyIndentLevel = 15; } void format() { @@ -325,10 +325,14 @@ private: if (Left.Tok.is(tok::semi) || Left.Tok.is(tok::comma)) return 0; - if (Left.Tok.is(tok::equal) || Left.Tok.is(tok::l_paren) || - Left.Tok.is(tok::pipepipe) || Left.Tok.is(tok::ampamp)) + if (Left.Tok.is(tok::l_paren)) return 2; + prec::Level Level = + getBinOpPrecedence(Line.Tokens[Index].Tok.getKind(), true, true); + if (Level != prec::Unknown) + return Level; + if (Right.Tok.is(tok::arrow) || Right.Tok.is(tok::period)) return 200; diff --git a/unittests/Format/FormatTest.cpp b/unittests/Format/FormatTest.cpp index b316750a0b..0d7901525b 100644 --- a/unittests/Format/FormatTest.cpp +++ b/unittests/Format/FormatTest.cpp @@ -456,6 +456,21 @@ TEST_F(FormatTest, BreaksDesireably) { " (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);"); } +TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) { + verifyFormat( + "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n" + " bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}"); + verifyFormat( + "if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" + " ccccccccccccccccccccccccc) {\n}"); + verifyFormat( + "if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n" + " ccccccccccccccccccccccccc) {\n}"); + verifyFormat( + "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n" + " ccccccccccccccccccccccccc) {\n}"); +} + TEST_F(FormatTest, AlignsStringLiterals) { verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n" " \"short literal\");");