draft proposal for Sum Types for D
Timon Gehr
timon.gehr at gmx.ch
Wed Nov 30 16:52:50 UTC 2022
On 11/30/22 04:39, Walter Bright wrote:
> On 11/29/2022 6:42 AM, Timon Gehr wrote:
>> Nice!
>
> Wow! I expected you to eviscerate it! :-)
> ...
Well, it looks useful and would allow me to easily replace some hacky
unsafe variant code I have written under time pressure before a
deadline. Then it would become memory safe. However, it could be a lot
more useful if it also allowed me to check that I got nothing wrong. ;)
>> I think this general design, where it behaves just like a tagged union
>> but @safe, makes sense for D. I _really_ wish bad element access
>> resulted in a compile-time error instead of a runtime error though.
>>
>> Basically, you could treat
>>
>> if(?s.member){
>>
>> }
>>
>> and
>>
>> assert(?s.member);
>>
>> specially, and only allow accesses to s.member if they are guarded by
>> one of them. By default, accessing members is disallowed. The user can
>> then choose between:
>>
>> if(?s.member){
>> writeln(s.member);
>> }
>>
>> and
>>
>> assert(?s.member);
>> writeln(s.member);
>>
>> To either check the tag manually or opt into the runtime error very
>> explicitly.
>
> I expect that when a user accesses s.member, he implicitly expects it to
> be that member. If it isn't, then it's a program bug and hence a fatal
> runtime error.
I don't like fatal runtime errors. I prefer compile time errors.
> Adding an assert() in front of it is redundant.
> ...
It's not redundant if it is a compile-time error by default. The
explicit assert is to opt into the runtime error, but normally I'd like
the compiler to check correct element access during compile time for my
sumtypes. Runtime errors that could have easily been catched at compile
time make the feature less useful than it can be. For me, type checking
case analysis during compile time is one of the main selling points of
sum types.
>
>> I think catching errors early during type checking is one of the most
>> compelling things about sum types in other languages, and it would be
>> great if D could get that in some way. The analysis does not have to
>> be particularly sophisticated. In particular, no control flow analysis
>> is required.
>
> The compiler could do:
>
> writeln(s.a);
> writeln(s.b); // compile time error
>
> with data flow analysis, because if all paths to the second use go
> through reading s.a, then s.b could not possibly be valid. It would be
> similar to:
>
> if (x == 0)
> {
> if (x == 1) deadCode();
> }
>
> which currently dmd does not do.
I want a compile time error for every wrong access. Maybe it will give
compile time errors for accesses that are correct. In those cases I can
either rewrite my code to make it easier to spot that it is actually
right or I can add an explicit assert to document that the program might
crash there in case there is a mistake.
More information about the Digitalmars-d
mailing list