[fpc-devel] [Suggestion] Enumeration range-check intrinsic
Michael Van Canneyt
michael at freepascal.org
Sat Jul 13 14:32:35 CEST 2019
On Sat, 13 Jul 2019, Jonas Maebe wrote:
> On 13/07/2019 13:52, Michael Van Canneyt wrote:
>>
>>
>> On Sat, 13 Jul 2019, Jonas Maebe wrote:
>>
>>> On 13/07/2019 13:28, J. Gareth Moreton wrote:
>>>> Okay, okay. So what do we do to stop all these bug reports and help
>>>> programmers who get caught out by case blocks raising access
>>>> violations? Are you effectively saying "don't ever use enumerations for
>>>> external files and network signals" etc?
>>>
>>> Declare your enumation types so that the lowest and highest valid value
>>> comprise the lowest and highest value representable by its storage:
>>>
>>> {$mode delphi}
>>> {$z1}
>>> type
>>> tmyenum = (ea, eb, ec, emax = 255);
>>>
>>> That behaves the same both in FPC and in Delphi.
>>
>> This is a completely pointless definition, since for effective use you
>> still need to add code to check that the value is a named one.
>
> That is exactly what this thread is about: the ability to manually check
> whether an enumeration value is one of the valid (named) values.
I know.
I simply do not want to change a type definition just to keep the compiler happy.
I want to define a type as dictated by my use case:
tmyenum = (ea, eb, ec)
and then some easy means to check if an ordinal value fits. Hence the Is/as.
I yesterday checked a database project I have. I counted 25 enumerateds
which are stored in the database. Without fail, for each type
there is somewhere code in a type helper:
if (MyDatabaseValue>=0) and (MyDatabaseValue<=Ord(High(TMyENum))) then
MyENumValue:=TEnum(MyDatabaseValue))
else
EConvertError.Create('Invalid value for TMyEnum : %d',[MyDatabaseValue])
If I can replace this with a simple
MyEnumValue:=MyDatabaseValue as TMyEnumValue
It makes life a lot easier. So this construct has my support.
That the case where you would write
if MyEnumValue is TMyEnumValue then
can 'by default' be optimized away because as far as the compiler is
concerned this is a tautology, is for me a perfectly acceptable and
defendable point of view. Even to such a degree that the compiler would
simply reject your code by not allowing is/at on a variable of the type
itself. Also defendable.
The check on a valid value using is/as should be done before the enum variable is
used/assigned.
I just want to make the check easier.
Michael.
More information about the fpc-devel
mailing list