[clang-format] Handle enum in Verilog
authorsstwcw <f0gukp2nk@protonmail.com>
Sat, 1 Apr 2023 17:08:31 +0000 (17:08 +0000)
committersstwcw <f0gukp2nk@protonmail.com>
Sat, 1 Apr 2023 17:09:44 +0000 (17:09 +0000)
Verilog has enum just like C.

Reviewed By: HazardyKnusperkeks, owenpan, MyDeveloperDay

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

clang/lib/Format/UnwrappedLineParser.cpp
clang/unittests/Format/FormatTestVerilog.cpp

index fdf5d85..e47d634 100644 (file)
@@ -1709,8 +1709,8 @@ void UnwrappedLineParser::parseStructuralElement(
       // enum definition can start a structural element.
       if (!parseEnum())
         break;
-      // This only applies for C++.
-      if (!Style.isCpp()) {
+      // This only applies to C++ and Verilog.
+      if (!Style.isCpp() && !Style.isVerilog()) {
         addUnwrappedLine();
         return;
       }
@@ -3541,7 +3541,15 @@ bool UnwrappedLineParser::parseEnum() {
          FormatTok->isOneOf(tok::colon, tok::coloncolon, tok::less,
                             tok::greater, tok::comma, tok::question,
                             tok::l_square, tok::r_square)) {
-    nextToken();
+    if (Style.isVerilog()) {
+      FormatTok->setFinalizedType(TT_VerilogDimensionedTypeName);
+      nextToken();
+      // In Verilog the base type can have dimensions.
+      while (FormatTok->is(tok::l_square))
+        parseSquare();
+    } else {
+      nextToken();
+    }
     // We can have macros or attributes in between 'enum' and the enum name.
     if (FormatTok->is(tok::l_paren))
       parseParens();
index 88ce082..3243d33 100644 (file)
@@ -338,6 +338,20 @@ TEST_F(FormatTestVerilog, Delay) {
                             "x = x;");
 }
 
+TEST_F(FormatTestVerilog, Enum) {
+  verifyFormat("enum { x } x;");
+  verifyFormat("typedef enum { x } x;");
+  verifyFormat("enum { red, yellow, green } x;");
+  verifyFormat("typedef enum { red, yellow, green } x;");
+  verifyFormat("enum integer { x } x;");
+  verifyFormat("typedef enum { x = 0 } x;");
+  verifyFormat("typedef enum { red = 0, yellow = 1, green = 2 } x;");
+  verifyFormat("typedef enum integer { x } x;");
+  verifyFormat("typedef enum bit [0 : 1] { x } x;");
+  verifyFormat("typedef enum { add = 10, sub[5], jmp[6 : 8] } E1;");
+  verifyFormat("typedef enum { add = 10, sub[5] = 0, jmp[6 : 8] = 1 } E1;");
+}
+
 TEST_F(FormatTestVerilog, Headers) {
   // Test headers with multiple ports.
   verifyFormat("module mh1\n"