On Monday, 7 August 2023 at 17:08:56 UTC, Salih Dincer wrote:
> final switch is not considered safe with enums because it can take interpolated values, resulting in a runtime error:
Wasn't Cecil concerned with how to ensure at compile time that for all values of an enum there is a handler? I'll post my unsent draft from before the restore here:
On Wednesday, 2 August 2023 at 18:19:55 UTC, Cecil Ward wrote:
> Am I right in thinking that final switch can be used to check that all the elements in an enum are handled in cases?
According to [1] this is the case if and only if the switch expression is of that enum type.
// compiles with dmd -version=X
// missing case qmark if compiled without version
import std.stdio;
import std.conv;
import std.exception;
enum terminators_t { percent = '%', colon = ':', qmark = '?' };
int main_ (string [] args)
{
enforce (args.length == 2, "need one arg");
enforce (args [1].length == 1, "arg must be one character");
auto input = args [1][0].to!terminators_t;
final switch (input) {
case terminators_t.percent:
"PERCENT".writeln;
break;
case terminators_t.colon:
"COLON".writeln;
break;
version (X) {
case terminators_t.qmark:
"QUESTION MARK".writeln;
break;
}
}
return 0;
}
int main (string [] args)
{
try return main_ (args);
catch (Exception e) {
stderr.writeln (e.msg);
return 1;
}
}
But I like it without indentation, switch and break:
import std.stdio;
import std.exception;
void percent () { "PERCENT".writeln; }
void colon () { "COLON".writeln; }
void qmark () { "QUESTION MARK".writeln; }
enum terminatorhandlers = [ // this is implicitly "final"
'%' : &percent,
':' : &colon,
'?' : &qmark,
];
int main_ (string [] args)
{
enforce (args.length == 2, "need one arg");
enforce (args [1].length == 1, "arg must be one character");
auto input = args [1] [0];
auto p = input in terminatorhandlers; // switch emulation
enforce (p, "unknown terminator " ~ input);
(*p) (); // call the registered action
return 0;
}
int main (string [] args)
{
try return main_ (args);
catch (Exception e) {
stderr.writeln (e.msg);
return 1;
}
}
[1] https://dlang.org/spec/statement.html#final-switch-statement