]> granicus.if.org Git - clang/commitdiff
Take operator precedence into account when splitting lines.
authorDaniel Jasper <djasper@google.com>
Mon, 24 Dec 2012 00:13:23 +0000 (00:13 +0000)
committerDaniel Jasper <djasper@google.com>
Mon, 24 Dec 2012 00:13:23 +0000 (00:13 +0000)
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

lib/Format/Format.cpp
unittests/Format/FormatTest.cpp

index 2a8fbd6e5e9a19049e73f41b414c3f1840744609..ad85a8ecf2237e3a7a98e737f90b7f7f7d2c09e3 100644 (file)
@@ -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;
 
index b316750a0b6bde27f73965e657aeb546c0753d82..0d7901525b82da75ab321cf472dbc38da22a0d11 100644 (file)
@@ -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\");");