[fpc-devel] Gaps in a non-contiguous enum

Michael Van Canneyt michael at freepascal.org
Tue Aug 16 09:37:23 CEST 2022



On Tue, 16 Aug 2022, Juha Manninen via fpc-devel wrote:

> On Thu, Aug 11, 2022 at 9:37 PM Martin Frb via fpc-devel <
> fpc-devel at lists.freepascal.org> wrote:
>
>> fpc code is still "unexpected".
>> It takes into account the MinValue
>>
>> type TMyEnum = (a=5, b=7);
>>
>> GetEnumName(pt, 5) // a
>> GetEnumName(pt, 6) // b // should be 7
>>
>> if it is just the nth name, then it should start at 0 (or if needs be at
>> 1).
>>
>
> And function GetEnumValue() is buggy.

It is not buggy. 
It does not support enumerateds with gaps, because RTTI does not support enumerateds with gaps.
It never has.

So if something needs fixing, it's FPC that needs to give an error when you try
to get RTTI for an enum with gaps, and amend the documentation for
GetEnumValue and GetEnumName.

This lack of RTTI info is completely Delphi compatible, by the way.

The following program prints 'Property info is null'
---
program rttitest;

{$APPTYPE CONSOLE}

{$R *.res}

uses
   System.SysUtils, System.Classes,
   TypInfo;


type
   TFruitMore = (fmApple=1, fmOrange=3, fmBanana=5, fmGrapes, fmPear);

   TMyClass = class(TComponent)
   private
     FFruit: TFruitMore;
   Published
     property Fruit : TFruitMore Read FFruit Write FFruit;
   end;

var
   I: Integer;
   PI : PPropInfo;
   EnumType: PTypeInfo;
   aClass : TMyClass;

begin
   aClass:=TMyClass.Create(Nil);
   PI:=GetPropInfo(aClass,'Fruit',tkAny);
   if PI=nil then
     Writeln('Property info is null')
   else if PI^.PropType=nil then
     Writeln('Type info is null')
   else
     begin
     EnumType:=PI^.PropType^;
     I := GetEnumValue(EnumType, 'fmBanana');  // Returns 3
     Writeln(I);
     I := GetEnumValue(EnumType, 'fmGrapes');  // Returns 4 which is an
     Writeln(I);
     end;
   Readln;
end.
---

If you change it to

   EnumType:=TypeInfo(TFruitMore);

Delphi will even write a compile-time error:

[dcc32 Error] rttitest.dpr(29): E2134 Type 'TFruitMore' has no type info

So what you want to do is simply not supported.

Gaps in enums are an ugly hack to allow importing C enums.

Don't use it in proper pascal code.

Michael.


More information about the fpc-devel mailing list