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

Ondrej Pokorny lazarus at kluug.net
Wed Jul 3 08:58:44 CEST 2019


On 02.07.2019 23:34, Jonas Maebe wrote:
> On 02/07/2019 22:31, Ondrej Pokorny wrote:
>> This is similar to the object-is operator that gets evaluated as well
>> even if the type of the left-side value is the type at right side:
>>
>> var
>>    Value: TPersistent;
>> begin
>>    Value := TPersistent(TObject.Create);
>>    IsValid := Value is TPersistent; // IsValid gains false
> This is an invalid program. If you compile with -CR, the program will
> abort with an error when the typecast is performed, because it will get
> replaced by an "as" operation. In that sense, "integer as enum" would
> indeed be somewhat similar, and -CR might even be extended to perform
> the same replacement of explicit typecasts with "as" operators for these
> types.

If you want to extend -CR to perform "integer as enum" on enum(integer), 
please do it consequently and perform "integer as ShortInt" also on 
ShortInt(integer) - do range checking on explicit typecasts for all 
simple types, not only enums. People will love you for this:

var
   S: ShortInt;
   I: Integer;
begin
   I := 130;
   S := ShortInt(I);
end;

shall now raise a range check error with -CR. You can even optimize the 
compiler to verify constants on compile-time:

var
   S: ShortInt;
begin
   S := ShortInt($FF);
end;

should not compile any more with -CR. Good idea.

BTW I was always convinced that an explicit typecast switches off range 
checking. And now I open the documentation 
https://www.freepascal.org/docs-html/prog/progsu65.html and I read this: 
(citation)
/If, at run-time, an index or enumeration type is specified that is out 
of the declared range of the compiler, then a run-time error is 
generated, and the program exits with exit code 201. This can happen 
when doing a typecast (implicit or explicit) on an enumeration type or 
subrange type./

This means that this program is documented to exit with code 201:

program Project1;
uses Classes;
{$R+}
var
   B: Boolean;
begin
   B := Boolean(3);
   Writeln(B);
end.

Why doesn't it?

Ondrej

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.freepascal.org/pipermail/fpc-devel/attachments/20190703/1ff2b6a3/attachment.html>


More information about the fpc-devel mailing list