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

J. Gareth Moreton gareth at moreton-family.com
Fri Jul 5 02:12:48 CEST 2019


It's not so much convenience... it's more the fact that the compiler can 
and will optimise out "if (MyValue>=ord(Low(TMyType))) and 
(MyValue<=Ord(High(TMyType))) then" because it has every reason to 
assume that MyValue cannot possibly take on a value that's less than 
Low(TMyType) or greater than High(TMyType), hence it gets shortcut and 
assumed to always be True.

When MyValue takes on an invalid value due to being read from a file, 
for example, then that's where problems occur because there's no 
clear-cut way to catch it.

Gareth aka. Kit


On 05/07/2019 01:04, Michael Van Canneyt wrote:
>
>
> 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.
> _______________________________________________
> fpc-devel maillist  -  fpc-devel at lists.freepascal.org
> https://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-devel
>
>

---
This email has been checked for viruses by Avast antivirus software.
https://www.avast.com/antivirus



More information about the fpc-devel mailing list