Hi all,
The attached patch adds two messages inspired by C compiler's -Wswitch-enum and -Wcovered-switch-default. Building on the recent label count refactoring, this was fairly straightforward.
- If a case statement on an ordinal does not contain labels for all values of the ordinal, and no else statement is given, raise a new warning (W6059). This is actually defined as an error in ISO7185 and a dynamic-violation in IEC10206.
- If a case statement has labels for the entire range of the type, and an (now never used) else statement is present, a warning "Unreachable code" is raised.
Both cases are clearly something where the compiler and programmer don't agree on something, hence drawing attention to these situations.
The checks are enabled only for enumerated types and small (1-byte) integers. In C, they are only for enumerated types, I added small types because they are often used as tag types, where this check is extra useful.
Now, the RFC part. I have a few open questions...
* does it make sense to do that to all integral types? In ISO mode, it's formally required for all case statements. I left it out for now as sometimes case..of is used as a shorthand for multiple in..[range], there would be more detections that look like false positives.
* in ISO mode, there are 2 solutions: in Standard Pascal, not covering the entire type is a compile-time error. In Extended Pascal, this is a runtime error. Which one is followed usually?
* Building the compiler itself cycles with -Sew, so it bails on the first occurrence of one of these issues - turns out they're all over the place. However... I think the warnings are correct and expose imperfect code here. Take this example (one of the first encountered):
<https://github.com/graemeg/freepascal/blob/master/compiler/defutil.pas#L1630> stringtype is an enum and all values are used. There cannot be any other values (as we have established last year). Therefore, the else clause is just as wrong as an "if false then", which would be caught already.
* Adding to the previous, since it is now possible to discover forgotten items or later additions by the other warning, removing these 'safety' else-clauses would improve code quality.
What do you think?
