Make an enum idiomatic D - enhancing GNU Bison's Dlang support
Bastiaan Veelo
Bastiaan at Veelo.net
Thu Sep 3 14:05:10 UTC 2020
On Wednesday, 2 September 2020 at 13:20:14 UTC, Adela Vais wrote:
> Thank you for your answer!
>
> The problem is that I need specifically the Bison-generated
> string representation, so S_YYEOF.toString should give "\"end
> of file\"", not "S_YYEOF".
I think what you want is also suggested by H.S. Teoh:
>> (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.)
What he means is you can define a free function that can be used
as if it were a member function or property of a type by using
UFCS. This is how (https://run.dlang.io/is/u3EBeW):
import std.stdio;
enum SymbolKindEnum {
S_YYEMPTY = -2, /* No symbol. */
S_YYEOF = 0, /* "end of file" */
S_YYerror = 1, /* error */
/* ... */
S_input = 14, /* input */
S_line = 15, /* line */
S_exp = 16, /* exp */
}
string toString(SymbolKindEnum kind) pure @nogc
{
final switch (kind) with(SymbolKindEnum) {
case S_YYEMPTY:
assert(false, "Tried representing no symbol as a
string.");
case S_YYEOF:
return `"end of file"`;
case S_YYerror:
return `error`;
/*...*/
case S_input:
return `input`;
case S_line:
return `line`;
case S_exp:
return `exp`;
}
}
void main()
{
auto kind = SymbolKindEnum.S_YYEOF;
writeln(kind.toString); // "end of file"
}
-- Bastiaan.
More information about the Digitalmars-d
mailing list