Make an enum idiomatic D - enhancing GNU Bison's Dlang support

H. S. Teoh hsteoh at
Tue Sep 1 18:18:06 UTC 2020

On Tue, Sep 01, 2020 at 05:47:24PM +0000, Adela Vais via Digitalmars-d wrote:
> I need some advice on how to modify the current form of an enum,
> SymbolKind, to make it more idiomatic D (or leave it as it is -
> similar to how it is handled for the C++ support).
> The problem is explained here [0]. (Java allows methods in enums [1].)
> The way I modified it is by wrapping it in a struct and adding
> functionalities to change the already existing interaction with the
> enum as little as possible [2]. The code I changed in the repository
> is written in M4, so I will add the output after Bison is run:

There is no need to wrap SymbolKind in any way.  Idiomatic D code can
easily introspect the enum to obtain its string representation; e.g.,
the standard library std.format already prints the string representation
when handed an enum:

	enum SymbolKind {
		S_YYEMPTY = -2,
		S_YY_EOF = 0,
		S_YYerror = 1,

	import std;
	pragma(msg, format("%d", SymbolKind.S_YYEMPTY));
	pragma(msg, format("%s", SymbolKind.S_YYEMPTY));


All you have to do is to ensure that when the enum value is to be
printed out, you specify to use the string representation.  Depending on
whether you choose to have @nogc compatibility, you may or may not use
std.format, but either way, it's not hard to obtain the string
representation of an enum value in D.

I'd only wrap an enum if I need to do something really rare and unusual,
like operator overloading or enum inheritance. For normal usage, I'd
just leave the enum the way it is. (Even adding methods to an enum can
be simulated with UFCS, so I wouldn't even wrap an enum in that case.
Only for truly unusual use cases would I do it.)


We've all heard that a million monkeys banging on a million typewriters will eventually reproduce the entire works of Shakespeare.  Now, thanks to the Internet, we know this is not true. -- Robert Wilensk

More information about the Digitalmars-d mailing list