No we should not support enum types derived from strings

deadalnix deadalnix at gmail.com
Mon May 10 21:44:02 UTC 2021


On Monday, 10 May 2021 at 12:19:07 UTC, deadalnix wrote:
> On Monday, 10 May 2021 at 04:21:34 UTC, Andrei Alexandrescu 
> wrote:
>> So you have a range r of type T.
>>
>> You call r.popFront().
>>
>> Obvioulsly the type of r should stay the same because in D 
>> variables don't change type.
>>
>> So... what gives, young Padawan?
>>
>> No, this is not subtyping 101.
>
> If you have a range of T, then you got to return a T. I'm not 
> sure what's the problem is here. Do you have a concrete example?
>
> All I can think of are things like slicing and alike, and they 
> should obviously return a string, not a T.

More to the point, consider this:

class String {
private:
     immutable(char)[] value;

public:
     this(immutable(char)[] value) { this.value = value; }

     // ...
}

class EnumString : String {
public:
     static EnumString value1() { return new EnumString("value1"); 
}
     static EnumString value2() { return new EnumString("value2"); 
}

private:
     this(immutable(char)[] value) { super(value); }
}

While the implementation differs, conceptually, from a the theory 
standpoint, this is the same. This is using a subtype to 
constrain instance of type (String here) to a certain et of 
possible values. When using the subtype (EnumString) you have the 
knowledge that it is limited to some value, and you lose that 
knowledge as soon as you convert to the parent type.

But instead, we gets some bastardised monster from the compiler, 
that's not quit a subtype, but that's not quite something else 
that really make sens either. As expected, this nonsense ends up 
spilling into user code, and then the standard lib, based on user 
constraints, and everybody is left choosing between bad tradeof 
down the road because the whole house of cards is built on shaky 
foundations.

The bad news is, there is already a language like this. It's 
called C++, and it's actually quite successful. With all due 
respect to you and Walter, you guys are legends, but I think 
there is also a bit of learned helplessness coming from both of 
you due to a lifetime of exposure to the soul corroding effects 
of C++.

This attitudes pervades everything, and most language constructs 
suffer of some form of it in one way or another, causing a 
cascade of bad side effects, starting with this whole thread. A 
few examples en vrac for instance: DIP1000, delegate context 
qualifiers, functions vs first class functions, etc...

Back to the case of enum, it is obviously and trivially a 
subtype. In fact, even the syntax is the same:

enum Foo: string { ... }

Handling enum strings should never have been a special that was 
added to phobos, because it should never have been a special to 
begin with, in phobos or elsewhere.


More information about the Digitalmars-d mailing list