Strange compiler behavior with generics [BUG?] lazarus / 8-Other ---------------------------------------------------------------------- soerensen3 · 2017-06-21 23:34 Hello, i have encountered a strange behavior with the compiler when using generics. I want to have a generic where define the parent class as a parameter. This way I can fake something like multiple inheritance. When I compile this code I get this error Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i   generic gTest < Test > = class ( Test ) // <-- Gives me this error: class type expected, but got ""  end;         This code again compiles fine if I make a constraint to the generic parameter. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i   generic gTest < Test: TPersistent > = class ( Test )    function Test123: String; // Some function. This even works with properties and constructors and so on  end;       Everything works as expected until I try the following: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i   generic gTest < Test: TPersistent > = class ( Test )    destructor Destroy; override; // <- Gives me: There is no method in an ancestor class to be overridden: "destructor Destroy;"    function Test123: String;  end; It says TPersistent does not have a virtual destructor which is simply not true. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i   TPersistent = class(TObject,IFPObserved)       ...    Destructor Destroy; override; Should I file a bug report? See attachment for the full code. ---------------------------------------------------------------------- molly · 2017-06-22 00:52 If you wish to inherit from TPersistent then you would have to tell the compiler that you wish so I think you wanted something like this: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program project1; {$MODE OBJFPC}{$H+} Uses  Classes; type  { gTest }  generic gTest = class(TPersistent)    destructor Destroy; override;    function Test123: String;  end;   TTest = specialize gTest; destructor gTest.Destroy;begin end; function gTest.Test123: String;begin  Result:= 'TestString';end; var  Test: TTest;begin  Test:= TTest.Create;  WriteLn( Test.Test123 );  Test.Free;end. Note the warning btw. Also note that the specialization makes no sense to me, unless it was intended. Perhaps it would be helpful to read up on generics wiki ? ---------------------------------------------------------------------- Thaddy · 2017-06-22 07:08 Well I could come up with this,maybe you mean something along those lines: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program Project1;{$mode delphi}uses classes; type  TPersistentclass = class of Tpersistent;  TMulti = class(TPersistent)  strict private  var a:T1;  var b:T2;  public    constructor create;    destructor destroy;override;    property class1:T1 read a;    property class2:T2 read b;  end;   constructor TMulti.Create;  begin     a:=T1.Classtype.Create as T1;  // note as is important here.     b:=T2.ClassType.Create as T2;  end;  destructor TMulti.Destroy; begin    b.free;  a.free;    inherited; end; var  a:TMulti;  // a new class type from Tcomponent and TStringlistbegin  a := TMulti.Create;  writeln(a.ClassName);  // The new class  writeln(a.Class1.ClassName); // the component  writeln(a.Class2.ClassName); // the stringlist  a.free;  readln;end. This works in trunk... It is a pity that code completion doesn't work with generics yet... Then this would be more useful. ---------------------------------------------------------------------- soerensen3 · 2017-06-22 10:50 Thanks for the answers and sorry for the confusion! @Molly: I did not mean to inherit TPersistent directliy. I will try to make a better sample. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i    generic gNamedObject < CParent > = class ( CParent )      private         FName: String;      published        property Name: String read FName write FName;   end;   TPersistentWithName = specialize gNamedObject < TPersistent >;  TStringListWithName = specialize gNamedObject < TStringList >;   generic gObjectWithChildren = class ( CParent )    private       type TCustomList = specialize TFPGObjectList;        var FChildren: TCustomList; //Should be initialized in constructor and destroyed in destructor     public     property Children: TCustomList read FChildren write FChildren;  end;    TNamedPersistentWithChildren = specialize gNamedObject < specialize gObjectWithChildren < TPersistent >>; So I have something like multiple inheritance because I can inherit from a generic with any object at any time to give it some behavior if needed. The above example works if I make a constraint to the generic parameter to be a descendant of TPersistent. I could have used TObject as well. This is not a big deal but in the lower generic I would need to introduce a constructor and destructor to initalize FChildren. This however leads to the message: QuoteThere is no method in an ancestor class to be overridden: "destructor Destroy;" While I think Thaddy got what I meant by multiple inheritance my actual question is, if this is a compiler bug, because there is a virtual destructor declared in TObject so any class should be able to override the Destroy method. ---------------------------------------------------------------------- Thaddy · 2017-06-22 12:31 Quote from: soerensen3 on June 22, 2017, 12:50:15 pmWhile I think Thaddy got what I meant by multiple inheritance my actual question is, if this is a compiler bug, because there is a virtual destructor declared in TObject so any class should be able to override the Destroy method. But that is exactly what I did.. Override the destructor... ---------------------------------------------------------------------- soerensen3 · 2017-06-22 13:39 @Thaddy: yes I didn't mean than in general you can not override the constructor but in my special case you can't. I think this is a bug in the compiler because every other virtual method can be overridden. So to summarize: generic without parameter used as a class descendant: Works even with overriding the destructor generic with parameter used as a class descendant: Works except for overriding the destructor Also interesting that the error occurs even without the specialize declaration. ---------------------------------------------------------------------- rvk · 2017-06-22 14:11 Could you create a complete reproducible example? You already said you didn't mean to inherit from TPersistent but five an example CParent. How does CParent look. If that again is inherited from TObject it should have the destructor to be overridden. This compiles: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i type  CParent = class(TPersistent)  end;   generic gTest = class(CParent)  public    destructor Destroy; override;    function Test123: string;  end; So please show your "special case" where you can't. ---------------------------------------------------------------------- soerensen3 · 2017-06-22 14:34 CParent can be any class type as any class inherits TObject. Ok try to compile the following program once as is and second with the define in the beginning enabled. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i    program GenericTest; {.$DEFINE WITHDESTRUCTOR}//REMOVE DOT IN THE BEGINNING TO ENABLE//WORKS WITH DEFINE DISABLED, DOES NOT WORK WITH DEFINE ENABLED {$mode objfpc}{$H+} uses  {$IFDEF UNIX}{$IFDEF UseCThreads}  cthreads,  {$ENDIF}{$ENDIF}  Classes,  fgl  { you can add units after this }; typegeneric gNamedObject < CParent: TObject > = class ( CParent )      private         FName: String;      published        property Name: String read FName write FName;   end;   TPersistentWithName = specialize gNamedObject < TPersistent >;  TStringListWithName = specialize gNamedObject < TStringList >;   generic gObjectWithChildren < CParent: TObject > = class ( CParent )  private       type TCustomList = specialize TFPGObjectList;       var FChildren: TCustomList; //Should be initialized in constructor and destroyed in destructor     public       constructor Create;       {$IFDEF WITHDESTRUCTOR}       destructor Destroy; override; //Here the error is raised that this method is not in the base class      {$ENDIF}        property Children: TCustomList read FChildren write FChildren;  end;   TPersistentWithChildren = specialize gObjectWithChildren < TPersistent >;  TNamedPersistentWithChildren = specialize gNamedObject < TPersistentWithChildren >; constructor gObjectWithChildren.Create;beginend; {$IFDEF WITHDESTRUCTOR}destructor gObjectWithChildren.Destroy;beginend;{$ENDIF} beginend. ---------------------------------------------------------------------- rvk · 2017-06-22 14:38 Maybe I'm completely off but why not Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i   generic gObjectWithChildren < CParent: TObject > = class ( TObject )Inherit from TObject in class(). CParent is not an object you can use in class(), is it? ---------------------------------------------------------------------- Thaddy · 2017-06-22 14:51 Quote from: soerensen3 on June 22, 2017, 04:34:03 pmCParent can be any class type as any class inherits TObject. You asked for TPersistent yourself!. Just replace it with "Tobject" (or better with "class") and my example still works as expected. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program Project1;{$mode delphiunicode}uses classes; type  TMulti = class  strict private  var a:T1;  var b:T2;  public    constructor create;    destructor destroy;override;  public    property class1:T1 read a;    property class2:T2 read b;  end;   constructor TMulti.Create;  begin     a:=T1.Classtype.Create as T1;   b:=T2.ClassType.Create as T2;  end;  destructor TMulti.Destroy; begin    b.free;    a.free;    inherited; end;  var  a:TMulti;begin  a := TMulti.Create;  writeln(a.ClassName);  writeln(a.Class1.ClassName);  writeln(a.Class2.ClassName);  a.free;  readln;end. Note I strongly suggest to use Delphi syntax for generics and not quirks mode. ---------------------------------------------------------------------- ASerge · 2017-06-22 15:03 The author tries to make a strange definition - to specify the template symbol as the base class. I think this is a compiler error. It must explicitly state error that the base type must be a class (as Delphi does in a similar construct). ---------------------------------------------------------------------- soerensen3 · 2017-06-22 15:09 @rvk: QuoteMaybe I'm completely off but why not Inherit from TObject in class(). Because it is not what I want. I want a generic that can be applied to any class to add new behavior. Therefore a Parent parameter is needed in the generic. QuoteCParent is not an object you can use in class(), is it? It's a variable you declared. CParent is the generic parameter: http://wiki.freepascal.org/Generics It is defined in the <..> brackets and serves as a placeholder for the generic parameter until specialized. @Thaddy: While your code works you will end up with an TObject descendand but with 2 properties instead of real inheritance, which is working as expected except for the destructor to be overridable. Anyway it is not the point how I can do it some other way but if it is a bug in the compiler or not that the code supplied does not compile. I believe yes but I wanted a second opinion. Hope this didn't sound rude, I only wanted to clearify! ---------------------------------------------------------------------- ASerge · 2017-06-22 15:20 Quote from: soerensen3 on June 22, 2017, 05:09:02 pm@rvk: QuoteMaybe I'm completely off but why not Inherit from TObject in class(). Because it is not what I want. I want a generic that can be applied to any class to add new behavior. Therefore a Parent parameter is needed in the generic. I suspect you do not really understand generics. Perhaps the class helper is more suitable for you? Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i {$APPTYPE CONSOLE}program Project1; uses Classes; type  TAnyClassHelper = class helper for TObject    function Test123: String;  end; function TAnyClassHelper.Test123: string;begin  Result := '123';end; var  X: TStream;begin  X := TMemoryStream.Create;  Writeln(X.Test123);  X.Free;  Readln;end. ---------------------------------------------------------------------- soerensen3 · 2017-06-22 16:02 I filed a bug report: https://bugs.freepascal.org/view.php?id=32054 I have the feeling that nobody really understands what I'm saying A class helper can not have fields so this is not possible for a class helper. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i generic gNamedObject < CParent: TObject > = class ( CParent )      private       FName: String;      published        property Name: String read FName write FName;   end; This code works with and can add the functionality of having a name to any class by specializing. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i TPersistentWithName = specialize gNamedObject < TPersistent >;  TStringListWithName = specialize gNamedObject < TStringList >; I can use many of these generics (and store eg. Positions, Lists with Children and so on) and specialize them in a chain so i get an object with multiple behaviors I define only once. So again the code above is valid and working. As any object has a destructor Destroy; virtual; it should be possible to override it in a generic. But it's not. For no reason I think. My only question is: Is this behavior a bug? If not what is the reason that you cannot override the destructor. ---------------------------------------------------------------------- Thaddy · 2017-06-22 18:45 No, it is a blatant programming error. You can't derive from an instance of a class in your case CParent, you must derive from the class, in your case TObject. That makes it clear. This is NOT a bug. Sorry. This is your mistake. That can only be done in scripting/dynamic languages and only at runtime, not compile time and I never saw this implemented like you propose. But your general idea in your original code is possible, as I showed. Also note it is possible to override a destructor in a generic class: again, I showed you how... I think you do not understand my code. And I refuse to rewrite it in quirks mode (objfpc style generics mode). ---------------------------------------------------------------------- soerensen3 · 2017-06-22 20:33 @Thaddy: CParent is a parameter not an instance and I already changed the syntax to delphi mode which is in this case deleting the specialize and generic keywords. Could you please have a look at the attachment in the bug post again. I'm sure you will see that this is not an instance. In case the colon in the generic parameter is your problem. If a generic parameter is followed by a colon the following type works as a constraint. This means the base type is at least of this class type (If you use a class). See this for more detail: http://docwiki.embarca dero.com/RADStudio/Tokyo/en/Constraints_in_Generics Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i type  TTest     < Type: TObject>  // TObject is a constraint here    class  end;  See the section about constaints http://docwiki.embarcadero.com/RADSt udio/Tokyo/en/Constraints_in_Generics ---------------------------------------------------------------------- Thaddy · 2017-06-22 20:57 First mistake: type is a reserved word... Don't be THAT stupid. Class too. I happen to know Pascal ignores white space... too. And you missed "=". Oh well. Checkout your code first. I already did my best to explain to you how to do that. My first code even uses a constraint properly: Tpersistent. And the second example I gave also constrains to TObject by using class. Now stop it. Try your code in Delphi . Does not work..... Try my code in Delphi: works. I wonder why that is ? And don't refer to documentation before you actually understand it, which you don't at the moment. ---------------------------------------------------------------------- soerensen3 · 2017-06-23 00:03 Just to show that it is possible to do something like multiple inheritance with generics run this code and have a look at the output. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i program Project1;{$APPTYPE CONSOLE}{$mode delphi}{$H+} uses  {$IFDEF UNIX}{$IFDEF UseCThreads}  cthreads,  {$ENDIF}{$ENDIF}  Classes  { you can add units after this }; type   { TShowClassParents }   TShowClassParents < T: class > = class ( T )  //generic that shows class parents    procedure WriteClassParents;  end;   { TNamedObject }   TNamedObject < T: class > = class ( T ) //generic with a name field    private      FName: String;     public      property Name: String read FName write FName;  end;  procedure TShowClassParents < T >.WriteClassParents;var  c: TClass;begin  c:= ClassType;  while Assigned ( C ) do // This will loop through all class parents and write them to the output    begin      WriteLn( C.ClassName );      c:= c.ClassParent;    end;end; type  //predeclare types as specializations cannot be passed as a parameter directly  TListShowParents = TShowClassParents < TList >; //A list with the WriteClassParents method  TNamedList = TNamedObject < TList >; //A List with a name field var  Ob: TShowClassParents < TPersistent >; // A persistent with the WriteClassParents method  Ob2: TNamedObject< TListShowParents >; // "Multiple inherit" first inherit TListShowParent then inherit TNamedObject  Ob3: TListShowParents< TNamedList >; // Do it the other way around begin  WriteLn( 'Class parents of Ob' );  Ob:= TShowClassParents < TPersistent >.Create;  Ob.WriteClassParents;  Ob.Free;   WriteLn;   WriteLn( 'Class parents of Ob2' );  Ob2:= TNamedObject < TListShowParents >.Create;  Ob2.WriteClassParents;  Ob2.Free;   WriteLn;   WriteLn( 'Class parents of Ob3' );  Ob3:= TShowClassParents < TNamedList >.Create;  Ob3.WriteClassParents;  Ob3.Free;end.  You can see that this is possible in Free Pascal even with Delphi Mode. I don't have Delphi so I cannot test it there. But in a generic like this I cannot inherit virtual methods from a base class. I think there is the compiler bug. That it complaints that the base class does not have this method at all while in the above case where no method is overridden it just compiles. ---------------------------------------------------------------------- molly · 2017-06-23 23:40 According to Delphi wiki: QuoteThe base type of a parameterized class or interface type might be an actual type or a constructed type. The base type might not be a type parameter alone. Whether or not the compiler should complain about that for your example code, i would have no idea (my personal opinion would be, yes the compiler should complain on faulty code). The type definition for FPC can be a bit ambiquitos in that regards... imho, another flaw with regards to your example is that you expect the generic to have a base type of class, while the compiler wouldn't know that from your declaration alone. Only when specialization comes into play the base type becomes clear. You could just as well meant for your generic template declaration to be a record. Your idea on how a generic should be declared seems a bit strange to me, and i was unable to find any example code (either from Delphi or FPC) that tries to use (only) a template for its base type. Because the base type is unknown/uncertain, then how would the compiler know which methods it inherits and can be overridden or not ? ---------------------------------------------------------------------- soerensen3 · 2017-06-24 20:00 ok, so you say the class constraint will also accept record types? I didn't know that. But I even tried TObject or TPersistent for a constraint, but it didn't help. I thought that the type checks for a generic were done in each specialization because it also cannot know the types of other variables which the compiler needs to know for the method bodies. But on the other hand generics are made for reducing redundant code, so I think it makes sense to program some basic behavior and apply it to different classes instead of copying code to many classes (and also maintain). While Thaddy's solution also solves this problem it feels more natural to me to call for example Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i Obj1.Name:= 'SomeName'; instead of Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i Obj1.SomeProp.Name:= 'SomeName'; but the advantage would be that you could add behaviors on runtime (without the generic part). ---------------------------------------------------------------------- molly · 2017-06-24 23:11 Let me first start by saying that generics is a bit out of my comfort- zone. I know the basics and use them as such but it can drive a person insane trying to grasp what code is actually produced when using generics that inherited from other generics , combining generics with or without interfaces (which can also be made out of generics). Quoteok, so you say the class constraint will also accept record types? No, not exactly (although i realize now, that it could perhaps be interpreted as such). I meant the opposite, because of what happens when you use a template for base type (again, note that this should not be allowed). But indulging your train of thought, the compiler would have no clue how to handle things until it reaches the specialization. consider the following: Code: [Select]type   TSomeRecord = record     SomeField: Integer;   end;   generic gTest2 = class(T)   end;   TG2a = specialize gTest2;   TG2b = specialize gTest2; And compilations of TGB2b specialization fails, for obvious reasons. QuoteI thought that the type checks for a generic were done in each specialization because it also cannot know the types of other variables which the compiler needs to know for the method bodies. I am not going to pretend that i know how the compiler actually solves things, but as far as i understood the base type must be declared before. Which brings us to the question whether or not the compilation of TG2a specialization should be at all possible or not (or if  the compiler should already complain at the generic declaration). Hence why i linked to the official type declaration for FPC generics, as that leaves room for such construct to be allowed (while Delphi seems to state things more explicitly in its documentation). QuoteWhile Thaddy's solution also solves this problem it feels more natural to me to call for example ... And imho that depends on what it is that you are actually trying to achieve, since you seem to have dismissed all other suggestion that were made in this thread. In basics (without looking any further) you seem to wish to inherit from another class and add new properties, something that btw can also be achieved by using a helper class. (but i realize that is not what you meant). So then it's starting to look more as if you expect templates to be a full blown form of macro's that are resolved at compile time and which are solved recursively. In that case, i suspect that you are trying to do too many things at once and try to wrap things up in a simple one/two-liner, but which would perhaps better be solved by using several small in between steps to achieve the desired result. But again, that entirely depends on what it is that you are actually trying to achieve. The simple examples that you have shown so far are not going to answer that. afaik not many (compiler) developers are paying close attention to these forums, so therefor you might perhaps have more luck on posting your question on the mailing list (if you haven't done so already). That could perhaps also result in better suited answers (at least better than the ones that i am able to produce).