[PATCH v2] enum: support declarations with a trailing comma

Alan Maguire <[email protected]>
Newsgroups dev.linux.lists.dtrace
Message-ID <[email protected]>
When doing python tracing, it was recently observed that #include'ing
a file with enum declarations with trailing commas fails; this is
due to the D grammar being strict about the last enumerator value
not having a trailing comma.  So

enum foo {
	BAR,
	BAZ
};

is permitted, but

enum foo {
	BAR,
	BAZ,
};

is not.  The latter pattern is used quite frequently in #include
files, especially where conditional compilation of some enum
values is done.

Relax this constraint and add a test to validate that D compilation
succeeds with the trailing comma in an enum declaration.

Signed-off-by: Alan Maguire <[email protected]>

Changes since v1:

- fixed commit description, updated test to cover enum, anon enum,
  typedef enum variations for both trailing comma case and without it
---
 libdtrace/dt_grammar.y                     |  3 +-
 test/unittest/enum/tst.EnumTrailingComma.d | 66 ++++++++++++++++++++++
 2 files changed, 68 insertions(+), 1 deletion(-)
 create mode 100644 test/unittest/enum/tst.EnumTrailingComma.d

diff --git a/libdtrace/dt_grammar.y b/libdtrace/dt_grammar.y
index 677cd869..7984b85d 100644
--- a/libdtrace/dt_grammar.y
+++ b/libdtrace/dt_grammar.y
@@ -702,7 +702,8 @@ enum_definition:
 
 enumerator_list:
 		enumerator
-	|	enumerator_list DT_TOK_COMMA enumerator
+	|	enumerator DT_TOK_COMMA enumerator_list
+	|	enumerator DT_TOK_COMMA
 	;
 
 enumerator:	DT_TOK_IDENT { dt_decl_enumerator($1, NULL); }
diff --git a/test/unittest/enum/tst.EnumTrailingComma.d b/test/unittest/enum/tst.EnumTrailingComma.d
new file mode 100644
index 00000000..fcf200e9
--- /dev/null
+++ b/test/unittest/enum/tst.EnumTrailingComma.d
@@ -0,0 +1,66 @@
+/*
+ * Oracle Linux DTrace.
+ * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved.
+ * Licensed under the Universal Permissive License v 1.0 as shown at
+ * http://oss.oracle.com/licenses/upl.
+ */
+
+/*
+ * ASSERTION:
+ * Enumerations should support declaration with a trailing comma for
+ * the last enumeration value as well as non-comma case.
+ *
+ * SECTION: Type and Constant Definitions/Enumerations
+ *
+ * NOTES:
+ *
+ */
+
+#pragma D option quiet
+
+enum colors {
+	RED = 1,
+	GREEN = 2,
+	BLUE = 3, 
+};
+
+enum weather {
+	CLOUDY,
+	SUNNY
+};
+
+enum {
+	CIRCLE,
+	SQUARE,
+	TRIANGLE,
+};
+
+enum {
+	HEXAGON,
+	OCTAGON
+};
+
+typedef enum {
+	RIGHT,
+	LEFT,
+} horizontal_t;
+
+typedef enum {
+	UP,
+	DOWN
+} vertical_t;
+
+typedef enum motor_transport {
+	CAR,
+	MOTORBIKE,
+} motor_transport_t;
+
+typedef enum nonmotor_transport {
+	BIKE,
+	SKATEBOARD
+} nonmotor_trasport_t;
+
+BEGIN
+{
+	exit(0);
+}
-- 
2.43.5
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.