]> granicus.if.org Git - clang/commitdiff
clang-format: [JS] Only special case top level object literal
authorDaniel Jasper <djasper@google.com>
Wed, 10 Jun 2015 09:21:09 +0000 (09:21 +0000)
committerDaniel Jasper <djasper@google.com>
Wed, 10 Jun 2015 09:21:09 +0000 (09:21 +0000)
assignments as enums.

Top level object literals are treated as enums, and their k/v pairs are put on
separate lines:

  X.Y = {
    A: 1,
    B: 2
  };

However assignments within blocks should not be affected:

  function x() {
    y = {a:1, b:2};
  }

This change fixes the second case. Patch by Martin Probst.

git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@239462 91177308-0d34-0410-b5e6-96231b3b80d8

lib/Format/TokenAnnotator.cpp
unittests/Format/FormatTestJS.cpp

index 78e6103bfcd5638bf027aa739f86724f34729fc0..8f2b608afb3344cdf1ee1e2e84e1510b9da229ec 100644 (file)
@@ -2088,13 +2088,14 @@ bool TokenAnnotator::mustBreakBefore(const AnnotatedLine &Line,
         Left.Previous->is(tok::char_constant))
       return true;
     if (Left.is(TT_DictLiteral) && Left.is(tok::l_brace) &&
-        Left.NestingLevel == 0 && Left.Previous &&
+        Line.Level == 0 && Left.Previous &&
         Left.Previous->is(tok::equal) &&
         Line.First->isOneOf(tok::identifier, Keywords.kw_import,
-                            tok::kw_export) &&
+                            tok::kw_export, tok::kw_const) &&
         // kw_var is a pseudo-token that's a tok::identifier, so matches above.
         !Line.First->is(Keywords.kw_var))
-      // Enum style object literal.
+      // Object literals on the top level of a file are treated as "enum-style".
+      // Each key/value pair is put on a separate line, instead of bin-packing.
       return true;
   } else if (Style.Language == FormatStyle::LK_Java) {
     if (Right.is(tok::plus) && Left.is(tok::string_literal) && Right.Next &&
index efa845cd90befbf7554ccfd21a66d454c696c099..59dcc0889acf856727a24ef30458a05fa7c1bd1f 100644 (file)
@@ -146,6 +146,10 @@ TEST_F(FormatTestJS, ContainerLiterals) {
   // Enum style top level assignment.
   verifyFormat("X = {\n  a: 123\n};");
   verifyFormat("X.Y = {\n  a: 123\n};");
+  // But only on the top level, otherwise its a plain object literal assignment.
+  verifyFormat("function x() {\n"
+               "  y = {z: 1};\n"
+               "}");
   verifyFormat("x = foo && {a: 123};");
 
   // Arrow functions in object literals.