[fpc-pascal] Background info on Generics in FPC

Sven Barth pascaldragon at googlemail.com
Sat Apr 17 23:19:29 CEST 2021


Am 17.04.2021 um 21:07 schrieb Graeme Geldenhuys via fpc-pascal:
> I'm looking at the wiki and official FPC language documentation. What was
> the reason for the decision to make the FPC syntax so verbose regarding
> Generics?

I don't know what the original reason was, but nowadays it's main 
advantage is that it avoids ambiguity. Take the following code:

=== code begin ===

someint := SomeGeneric<SomeType> + 42;

=== code end ===

The problem is that Delphi allows overloading of generic types with 
non-generic types, variables, constants and routines, thus up until the 
SomeType the code could in fact be the following as well:

=== code begin ===

var
   SomeType,
   SomeGeneric: LongInt;
   someint: Boolean;
begin
   someint := SomeGeneric<SomeType;
end;

=== code end ===

The compiler's parser has a very limited look ahead and thus especially 
with more complex specializations (especially nested ones) and type 
overloads in scope the compiler might not come to the right decision 
(e.g. it decided to parse it as a specialization, but it should have 
been a non-generic expression instead) and then it would need to do back 
tracking.

Delphi's parser handles such cases correctly, but FPC's parser is 
currently simply not capable of that. Thus the "specialize" keyword 
definitely helps to differentiate between a non-generic expression and a 
specialization. This also means that the non-Delphi modes currently can 
handle more complex expressions involving generics than mode Delphi can.

And for the "generic" keyword one could say that this way it is clear 
that one can't use the type as is and instead one must specialize them 
(also remember that originaly FPC did not support inline 
specializations; instead you had to do a type declaration for each 
specialization you wanted).

Regards,
Sven


More information about the fpc-pascal mailing list