No we should not support enum types derived from strings
deadalnix
deadalnix at gmail.com
Wed May 12 15:30:37 UTC 2021
On Wednesday, 12 May 2021 at 13:39:50 UTC, Andrei Alexandrescu
wrote:
> One matter is to distinguish what can be done from what D has
> already done and cannot change. For example, I tried some code
> just now and was... surprised.
>
> Meta mentioned that increment works with enums, and lo and
> behold it does:
>
> void main() {
> import std;
> enum X : int { x = 10, y = 20 }
> X x;
> writeln(x);
> ++x;
> writeln(x);
> }
>
> That prints "x" and then "cast(X)11". Meaning you can easily
> write a program that takes you outside enumerated values
> without a cast, which somewhat dilutes the value of "final
> switch" and the general notion that enumerated types are a
> small closed set. Arguably ++ should not be allowed on
> enumerated values.
>
> Surprises go on:
>
> void main() {
> import std;
> enum X : string { x = "Hello, world!", y = "xyz" }
> X x;
> writeln(x);
> x = x[1 .. $];
> writeln(x);
> }
>
> That prints:
>
> x
> cast(X)ello, world!
>
> which showcases, as a little distraction, a bug in the
> formatting of enums - the string should be quoted properly.
>
> But the larger point is that enum types derived from string
> actually allow, again, stepping outside their universe with
> ease.
>
I've raised these problem on a regular basis for years now.
This is obviously another instance where things are unsound, and
needs to be fixed.
Last time I we had a discussion on the matter, it went in a loop
that is best summarized as this:
enum E : int { A, B, C }
while (true) {
Me: A | B ought to be an int, not an E.
W&A: But you need it to be an enum, so that you can do things
like combining flags and stay. As in:
enum Mode { Read, Write }
openFile(file, Mode.Read | Mode.Write);
Me: Wl then, you can't have final switch, because you don't
have the guarantee it rely on.
W&A: final switch is very much needed, from X, Y Z reason.
}
This is extremely tiresome and kinda looks like the current
discussion (or another one would be the in contract needing to be
statically bound, where Timon and Myself had to fish for Bertrand
Meyer because nothing short of an argument from authority could
do the trick).
So if we get nothing else out of that discussion, fixing enum so
that they don't go out of the allowed set of value would be nice.
It's just unfortunate that it takes literally 5 years+ to get to
a point where this is even acknowledged as being an issue.
I hope we can somehow shorten that process, because it's not
workable as it is. You have people around like Timon and myself
who have an eye for this. It's free brainpower you are leaving
not leveraging.
More information about the Digitalmars-d
mailing list