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

Ondrej Pokorny lazarus at kluug.net
Thu Jul 11 12:52:49 CEST 2019


On 11.07.2019 11:58, J. Gareth Moreton wrote:
>
> Done!
>
Thank you for your work!

BTW, your note in the issue report is very misleading: 
https://bugs.freepascal.org/view.php?id=33603#c117162.

 > The idea behind "is" and "as" is that they are the sole exception to 
the rule and will return False and raise an error respectively if the 
enum is out of bounds.

IS/AS are not an exception of the rule - after a long discussion we 
settled down that if IS/AS is applied on a value of the same enumeration 
type:

var
   MyEnumValue: TEnumValue;
begin
   if MyEnumValue is TEnumValue then
// ...
end;

the compiler will expect that the result is always true. (It doesn't 
have to check for invalid values.)

When I read the following sentence:
 > If the value falls within a hole, then it will pass - currently only 
in Delphi mode though. FPC mode won't allow it.

I think you mixed up "normal enums" and "enums with holes" and so the 
note in the issue report doesn't make any sense.

----

The conclusion is:
1.) IS/AS works reliably only on valid values on the left side of the 
operator. (Like any other function/intrinsic/operator in FPC.)
2.) If an invalid value is to be expected, IS/AS must be executed on an 
ordinal value (Integer, SmallInt, ...) before assigning it to the 
enumeration value. It cannot be executed on the resulting enumeration 
value to check its validity.
3.) IS/AS can be used also on "enumerations with holes". In this respect 
only the low/high bounds are checked, not the holes inside the valid range.
4.) IS/AS can be also used on ordinal types:
  - 4a.) (MyInt64Value is Integer) is a reasonable check if MyInt64Value 
is in Integer range.
  - 4b.) (MyIntegerValue is Int64) is not reasonable (Integer falls 
always into Int64 range) and will always return True and can/will be 
optimized by the compiler to return a True constant.

Ondrej



More information about the fpc-devel mailing list