[fpc-devel] [Suggestion] Enumeration range-check intrinsic

Jonas Maebe jonas at freepascal.org
Sat Jul 13 12:48:57 CEST 2019


On 11/07/2019 15:46, J. Gareth Moreton wrote:
> Outside of typecasting, there isn't a reliable way to check if an enum
> contains a valid value

Typecasting is not a reliable way. There is no and cannot be a reliable
way, period.

> For my personal point of view, I would like these operators to be the
> exception to the rule of the compiler assuming an enum always contains a
> valid value,

This is the crux of the whole issue. Type systems do not and cannot work
this way. At its heart, this discussion is not about compiler
assumptions, optimisations, exploiting undefined behaviour etc.

It's that if a language has a type system, then by definition all
reasoning over programs written in this language must follow the rules
of this type system. A fundamental part of this is that a variable of
type X can store all values that are valid for type X. Not more, and not
less.

This is true for FPC, Delphi, C, C++, C#, Java, ADA any every other
programming language in existence that has a type system. Otherwise you
do not have a type system, but at most some ad hoc behaviours that
vaguely resemble a type system. You can never deviate from this, or you
end up with an unmaintainable and unpredictable mess (regardless of how
well you know the basic rules of the language, and not just when you are
used to type system with different rules).

In Delphi's type system (and in C, C++, and C#), the valid values for an
enum are always all values that fit within its storage size, and that
storage size is fixed.

In FPC's type system (and in Ada and Java), the valid values for an an
enum are only the values between the lowest and the highest declared
enum element (in Java it's even more strict, in that when you have
"enums with holes", the holes are also invalid), regardless of the
storage size. Moreover, this storage size can vary depending on whether
or not the item is in bitpacked storage. That definition of enums is
also what allows us to bitpack these types in the first place, since
otherwise we would not be able to store all valid values for enums in
their bitpacked versions.


Jonas


More information about the fpc-devel mailing list