[clang] [clang-format] Do not break on JS fields like on goto labels (PR #76233)

Ilya Biryukov via cfe-commits cfe-commits at lists.llvm.org
Fri Dec 22 05:20:08 PST 2023


https://github.com/ilya-biryukov created https://github.com/llvm/llvm-project/pull/76233

This regressions was introduced in 70d7ea0cebcf363cd0ddcfb76375fb5fada87dd5. 
The commit moved some code and correctly picked up an explicit check for not running on Verilog.
However, the moved code also never ran for JavaScript and after the commit we run it there and
this causes the wrong formatting of:

```js
export type Params = Config&{
  columns: Column[];
};
```
into
```js
export type Params = Config&{
columns:
  Column[];
};
```

>From a21ed6f78f305a4910dc355d8ad31da04d81b86e Mon Sep 17 00:00:00 2001
From: Ilya Biryukov <ibiryukov at google.com>
Date: Fri, 22 Dec 2023 14:09:22 +0100
Subject: [PATCH] [clang-format] Do not break on JS fields like on goto labels

This regressions was introduced in 70d7ea0cebcf363cd0ddcfb76375fb5fada87dd5.
In addition to an explicit check for Verilog, the moved code also never
ran for JavaScript, which causes unwanted formatting turning:

```js
export type Params = Config&{
  columns: Column[];
};
```
into
```js
export type Params = Config&{
columns:
  Column[];
};
```
---
 clang/lib/Format/UnwrappedLineParser.cpp | 6 ++++--
 clang/unittests/Format/FormatTestJS.cpp  | 6 ++++++
 2 files changed, 10 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Format/UnwrappedLineParser.cpp b/clang/lib/Format/UnwrappedLineParser.cpp
index c38b4c884070bb..684609747a5513 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -1650,8 +1650,10 @@ void UnwrappedLineParser::parseStructuralElement(
       return;
     }
     // In Verilog labels can be any expression, so we don't do them here.
-    if (!Style.isVerilog() && Tokens->peekNextToken()->is(tok::colon) &&
-        !Line->MustBeDeclaration) {
+    // JS doesn't have macros, and within classes colons indicate fields, not
+    // labels.
+    if (!Style.isJavaScript() && !Style.isVerilog() &&
+        Tokens->peekNextToken()->is(tok::colon) && !Line->MustBeDeclaration) {
       nextToken();
       Line->Tokens.begin()->Tok->MustBreakBefore = true;
       FormatTok->setFinalizedType(TT_GotoLabelColon);
diff --git a/clang/unittests/Format/FormatTestJS.cpp b/clang/unittests/Format/FormatTestJS.cpp
index e185eceb353057..3aded8f3726d8b 100644
--- a/clang/unittests/Format/FormatTestJS.cpp
+++ b/clang/unittests/Format/FormatTestJS.cpp
@@ -2836,5 +2836,11 @@ TEST_F(FormatTestJS, AlignConsecutiveAssignmentsAndDeclarations) {
                Style);
 }
 
+TEST_F(FormatTestJS, DontBreakFieldsAsGoToLabels) {
+  verifyFormat("export type Params = Config&{\n"
+               "  columns: Column[];\n"
+               "};");
+}
+
 } // namespace format
 } // end namespace clang



More information about the cfe-commits mailing list