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

Adela Vais adela.vais99 at gmail.com
Wed Sep 2 13:20:14 UTC 2020


On Tuesday, 1 September 2020 at 18:18:06 UTC, H. S. Teoh wrote:
> 	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));
>
> Output:
> 	-2
> 	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.


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 I *can* change the name of the elements of the structure, 
but I don't think it's a great idea, as they are also 
automatically generated by Bison and the other languages' parsers 
leave them as is.

The string representation is needed only in case of an error 
output message. The enum's members are used as integers 
throughout the program, so I can't do something like:

   enum SymbolKind {
     S_YYEOF = "\"end of file\"",
     S_YYerror = "error",
     ...
   }

Based on what you said about using UFCS in my advantage, I 
thought about adding a method (to the class that contains the 
enum) that gives the string representation. But I have to think 
about how I can avoid a call like this.toString(token). Should I 
try to do this?


More information about the Digitalmars-d mailing list