final switch traps and improvements
bearophile
bearophileHUGS at lycos.com
Sun Dec 23 23:11:17 PST 2012
Recently Ada 2012 was accepted as ISO standard, and on the good
Lambda the Ultimate blog there is a small thread about it, with
an interesting post:
http://lambda-the-ultimate.org/node/4661#comment-73731
The post makes two simple valid points, worth considering.
Currently in D this code compiles with no errors:
void main() {
bool b;
final switch (b) {
case true:
break;
}
}
And gives at run-time:
core.exception.SwitchError at test(3): No appropriate switch clause
found
It's one of my top fifteen bug reports (it was mislabelled as
enhancement request):
http://d.puremagic.com/issues/show_bug.cgi?id=5713
In my opinion It's a topic worth discussing and fixing.
The simplest solution is to statically disallow "final switch" to
operate on anything bug enums.
A better solution is to make it work correctly where it can, and
statically disallow the other situations. This means a final
switch on bool must require both true and false cases. If the
final switching is on a "uint % 3" expression then the compiler
must statically require all the 0,1,2 cases and nothing else.
If part of all of this enhancement request gets accepted, then
other useful final switch situations are worth supporting:
http://d.puremagic.com/issues/show_bug.cgi?id=596
One common use case is with Nullable, but syntactically speaking
this is not good enough:
import std.typecons: Nullable;
void main() {
auto n = Nullable!int(5);
final switch (n) {
case Nullable(false, _): ...
case Nullable(true, _): ...
}
}
Bye,
bearophile
More information about the Digitalmars-d
mailing list