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

Ondrej Pokorny lazarus at kluug.net
Sat Jul 13 20:53:09 CEST 2019


On 13.07.2019 13:47, J. Gareth Moreton wrote:
> Here lies the problem - if you have a enumeration stored in a byte 
> field, say, in a file, and there's a chance it's been corrupted, 
> there's no reliable way to detect that, since even typecasting may not 
> be reliable, and once again I'm implying that enums are unsafe to use, 
> but right now, what else can one do?

Don't forget about my second suggestion: add internal range checking for 
enumeration values on specific operations: 
https://lists.freepascal.org/pipermail/fpc-devel/2019-July/041499.html

The "BUT (big BUT)" section in the 2nd half of the email. I copy it here 
with one small update:

BUT (big BUT): I suggest to do an enumeration/subrange validity check on 
the compiler side when range checking is used. This is similar to the 
current fpc_check_object intrinsic.

When range checking is used, this check should be injected (at least) 
before every case-of and the new is/as operators if they are replaced 
with true. When range checking is disabled, the check should not be 
injected at all. Examples for range checking:

1.) case MyEnumValue of // <<< here an enumeration validity check should 
be injected
2.) IsValid := SomeValue is TEnumValue; //  <<< here an enumeration 
validity check should be injected if SomeValue is an enumeration type. 
(It doesn't make sense for normal ordinal values like Integer because 
they are valid in the whole stored range.)
That would catch the
IsValid := MyEnumValue is TEnumValue;
check - it would be replaced by a TRUE constant but there would still be 
a range check injected that would raise an error in case MyEnumValueis 
not valid.

IMO such a solution is acceptable for both sides:
1.) Jonas' point: The clarity of the language will stay untouched 
because the new validity check will be only informative and used only 
for debugging without any assurance of correctness. (You see the 
difference: MyEnumValue is TEnumValue will raise an exception for an 
invalid value and not return false! False will be returned only for 
(MyInt is TEnumValue) if MyInt is ot of the range of TEnumValue.)

2.) My/J.Gareth's point: We will get an information about invalid enum 
values (range check error) instead of "undefined behavior" when 
debugging - and we
will be able to find code where invalid enum values can occur and fix 
the code where these values were assigned. Although this information may 
not be (theoretically) absolutely accurate (the same as fpc_check_object 
is not absolutely accurate), it will still be pretty accurate and it 
will be a big help during the debugging.

Ondrej



More information about the fpc-devel mailing list