r369916 - clang-format: [JS] handle `as const`.

Martin Probst via cfe-commits cfe-commits at lists.llvm.org
Mon Aug 26 08:37:05 PDT 2019


Author: mprobst
Date: Mon Aug 26 08:37:05 2019
New Revision: 369916

URL: http://llvm.org/viewvc/llvm-project?rev=369916&view=rev
Log:
clang-format: [JS] handle `as const`.

Summary:
TypeScript 3.4 supports casting into a const type using `as const`:

    const x = {x: 1} as const;

Previously, clang-format would insert a space after the `const`. With
this patch, no space is inserted after the sequence `as const`.

Reviewers: krasimir

Subscribers: cfe-commits

Tags: #clang

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

Modified:
    cfe/trunk/lib/Format/TokenAnnotator.cpp
    cfe/trunk/unittests/Format/FormatTestJS.cpp

Modified: cfe/trunk/lib/Format/TokenAnnotator.cpp
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/lib/Format/TokenAnnotator.cpp?rev=369916&r1=369915&r2=369916&view=diff
==============================================================================
--- cfe/trunk/lib/Format/TokenAnnotator.cpp (original)
+++ cfe/trunk/lib/Format/TokenAnnotator.cpp Mon Aug 26 08:37:05 2019
@@ -2746,6 +2746,10 @@ bool TokenAnnotator::spaceRequiredBefore
                        tok::kw_void))
         return true;
     }
+    // `foo as const;` casts into a const type.
+    if (Left.endsSequence(tok::kw_const, Keywords.kw_as)) {
+      return false;
+    }
     if ((Left.isOneOf(Keywords.kw_let, Keywords.kw_var, Keywords.kw_in,
                       tok::kw_const) ||
          // "of" is only a keyword if it appears after another identifier

Modified: cfe/trunk/unittests/Format/FormatTestJS.cpp
URL: http://llvm.org/viewvc/llvm-project/cfe/trunk/unittests/Format/FormatTestJS.cpp?rev=369916&r1=369915&r2=369916&view=diff
==============================================================================
--- cfe/trunk/unittests/Format/FormatTestJS.cpp (original)
+++ cfe/trunk/unittests/Format/FormatTestJS.cpp Mon Aug 26 08:37:05 2019
@@ -1479,6 +1479,9 @@ TEST_F(FormatTestJS, TypeAnnotations) {
       "                    .someFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
   verifyFormat("const xIsALongIdent:\n""    YJustBarelyFitsLinex[];",
       getGoogleJSStyleWithColumns(20));
+  verifyFormat("const x = {\n"
+               "  y: 1\n"
+               "} as const;");
 }
 
 TEST_F(FormatTestJS, UnionIntersectionTypes) {




More information about the cfe-commits mailing list