[clang] 2b30bd2 - clang-format: [JS] do not collapse - - to --.

Martin Probst via cfe-commits cfe-commits at lists.llvm.org
Tue Mar 30 05:32:24 PDT 2021


Author: Martin Probst
Date: 2021-03-30T14:31:24+02:00
New Revision: 2b30bd2be0a898d0e7cb9eb3f2cf0e0efeaa83e9

URL: https://github.com/llvm/llvm-project/commit/2b30bd2be0a898d0e7cb9eb3f2cf0e0efeaa83e9
DIFF: https://github.com/llvm/llvm-project/commit/2b30bd2be0a898d0e7cb9eb3f2cf0e0efeaa83e9.diff

LOG: clang-format: [JS] do not collapse - - to --.

In JavaScript, `- -1;` is legal syntax, the language allows unary minus.
However the two tokens must not collapse together: `--1` is prefix
decrement, i.e. different syntax.

Before:

    - -1; ==> --1;

After:

    - -1; ==> - -1;

This change makes no attempt to format this "nicely", given by all
likelihood this represents a programming mistake by the user, or odd
generated code.

The check is not guarded by language: this appears to be a problem in
Java as well, and will also be beneficial when formatting syntactically
incorrect C++ (e.g. during editing).

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

Added: 
    

Modified: 
    clang/lib/Format/TokenAnnotator.cpp
    clang/unittests/Format/FormatTestJS.cpp

Removed: 
    


################################################################################
diff  --git a/clang/lib/Format/TokenAnnotator.cpp b/clang/lib/Format/TokenAnnotator.cpp
index 34c291ecc492..5177dca751d9 100755
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3370,6 +3370,12 @@ bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
              Style.BitFieldColonSpacing == FormatStyle::BFCS_Before;
     return true;
   }
+  // Do not merge "- -" into "--".
+  if ((Left.isOneOf(tok::minus, tok::minusminus) &&
+       Right.isOneOf(tok::minus, tok::minusminus)) ||
+      (Left.isOneOf(tok::plus, tok::plusplus) &&
+       Right.isOneOf(tok::plus, tok::plusplus)))
+    return true;
   if (Left.is(TT_UnaryOperator)) {
     if (!Right.is(tok::l_paren)) {
       // The alternative operators for ~ and ! are "compl" and "not".

diff  --git a/clang/unittests/Format/FormatTestJS.cpp b/clang/unittests/Format/FormatTestJS.cpp
index 8963c9f19024..91a98bf64c5c 100644
--- a/clang/unittests/Format/FormatTestJS.cpp
+++ b/clang/unittests/Format/FormatTestJS.cpp
@@ -276,6 +276,12 @@ TEST_F(FormatTestJS, UnderstandsJavaScriptOperators) {
   // ES6 spread operator.
   verifyFormat("someFunction(...a);");
   verifyFormat("var x = [1, ...a, 2];");
+
+  // "- -1" is legal JS syntax, but must not collapse into "--".
+  verifyFormat("- -1;", " - -1;");
+  verifyFormat("-- -1;", " -- -1;");
+  verifyFormat("+ +1;", " + +1;");
+  verifyFormat("++ +1;", " ++ +1;");
 }
 
 TEST_F(FormatTestJS, UnderstandsAmpAmp) {


        


More information about the cfe-commits mailing list