Make an enum idiomatic D - enhancing GNU Bison's Dlang support
Petar
Petar
Wed Sep 2 17:43:31 UTC 2020
On Wednesday, 2 September 2020 at 13:20:14 UTC, Adela Vais wrote:
> On Tuesday, 1 September 2020 at 18:18:06 UTC, H. S. Teoh 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 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?
One design pattern that you can use is attaching additional
information to each enum member by using UDAs [1]. Here's an
example:
https://run.dlang.io/gist/PetarKirov/f725d1f7e22d7a31860898d2d37489d0
That way you can keep the same integer-based enum, but associate
with each element arbitrary things like strings, struct objects,
types, functions, etc.
[1]: http://ddili.org/ders/d.en/uda.html
More information about the Digitalmars-d
mailing list