[fpc-devel] [Suggestion] Enumeration range-check intrinsic
Michael Van Canneyt
michael at freepascal.org
Fri Jul 5 02:04:01 CEST 2019
On Thu, 4 Jul 2019, Jonas Maebe wrote:
>> Be it implicit assignments in object creation,
>> clearing records with Default(TMyRecord), reading records from streams
>> etc etc.
>> The issue is here and it needs some solution. If you don't like
>> "is" for this purpose, why not to introduce a compiler intrinsic
>> Valid(MyValue) that would check if MyValue is within the allowed range
>> of its type?
>
> Because it means that not a single transformation or check in the
> compiler can assume that MyValue contains a valid value. Either the
> compiler can assume validity and the manual check does not make any
> sense, or the compiler cannot assume it and then the language's type
> system becomes meaningless (*), and bitpacked arrays/records should be
> removed from the language.
>
> The whole point of a type system is that
> a) the programmer is responsible to ensure variables are filled with
> valid values when bypassing the type system (explicit typecasts, inline
> assembly, variant records, absolute variables, "external" aliases, ...)
Correct.
But the whole idea of the intrinsic for enumerated is simply to save typing.
basically
if (myvalue>=ord(Low(TMyType))) and (MyValue<=Ord(High(TMyType))) then
becomes
if IsValid(myvalue,TMyType) then // or myvalue is TMyType or IsValid(MyValue)
The languague is full of such constructs already: "is" and "as". "for...in"
SizeOf(), default(), assert().
These are all convenience methods, none of them are infallible:
"Is" and "As" can also fail. Default can also fail.
'implicitly initialized global variables' can also fail.
This has not stopped anyone from adding them.
So I see no reason why we should not add this convenience method:
It is not at odds with the fact that the compiler can assume that an
enumerated value is in range.
Michael.
More information about the fpc-devel
mailing list