瀏覽代碼

clang-format: [JS] support fields with case/switch/default labels.

Summary:
`case:` and `default:` would normally parse as labels for a `switch` block.
However in TypeScript, they can be used in field declarations, e.g.:

    interface I {
      case: string;
    }

This change special cases parsing them in declaration lines to avoid wrapping
them.

Reviewers: djasper

Subscribers: klimek, cfe-commits

Differential Revision: https://reviews.llvm.org/D36148

git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@310070 91177308-0d34-0410-b5e6-96231b3b80d8
Martin Probst 8 年之前
父節點
當前提交
7777ca006a
共有 2 個文件被更改,包括 20 次插入0 次删除
  1. 14 0
      lib/Format/UnwrappedLineParser.cpp
  2. 6 0
      unittests/Format/FormatTestJS.cpp

+ 14 - 0
lib/Format/UnwrappedLineParser.cpp

@@ -326,6 +326,11 @@ void UnwrappedLineParser::parseLevel(bool HasOpeningBrace) {
       break;
     case tok::kw_default:
     case tok::kw_case:
+      if (Style.Language == FormatStyle::LK_JavaScript && Line->MustBeDeclaration) {
+        // A 'case: string' style field declaration.
+        parseStructuralElement();
+        break;
+      }
       if (!SwitchLabelEncountered &&
           (Style.IndentCaseLabels || (Line->InPPDirective && Line->Level == 1)))
         ++Line->Level;
@@ -953,13 +958,22 @@ void UnwrappedLineParser::parseStructuralElement() {
     parseDoWhile();
     return;
   case tok::kw_switch:
+    if (Style.Language == FormatStyle::LK_JavaScript && Line->MustBeDeclaration)
+      // 'switch: string' field declaration.
+      break;
     parseSwitch();
     return;
   case tok::kw_default:
+    if (Style.Language == FormatStyle::LK_JavaScript && Line->MustBeDeclaration)
+      // 'default: string' field declaration.
+      break;
     nextToken();
     parseLabel();
     return;
   case tok::kw_case:
+    if (Style.Language == FormatStyle::LK_JavaScript && Line->MustBeDeclaration)
+      // 'case: string' field declaration.
+      break;
     parseCaseLabel();
     return;
   case tok::kw_try:

+ 6 - 0
unittests/Format/FormatTestJS.cpp

@@ -242,6 +242,12 @@ TEST_F(FormatTestJS, ReservedWords) {
   verifyFormat("var interface = 2;");
   verifyFormat("interface = 2;");
   verifyFormat("x = interface instanceof y;");
+  verifyFormat("interface Test {\n"
+               "  x: string;\n"
+               "  switch: string;\n"
+               "  case: string;\n"
+               "  default: string;\n"
+               "}\n");
 }
 
 TEST_F(FormatTestJS, ReservedWordsMethods) {