Old thread. It was suggested to me to create new thread, as old one has been inactive for too long.
As I see, anonymous methods aren't implemented in FPC yet and there is no plans to add them. I personally need them for my projects to be ported from Delphi to FPC, cuz I want them to be Linux compatible. Why do I need anonymous methods? They're very useful every time, when I need to:
1) Wrap some arbitrary data into interface in order to pass it to another object, when implementation should be as universal, as possible (in case of generics for example). Export data from generic to some other arbitrary object for example.
2) There is data, that need to be passed to many functions, so best way to do it - create object, turn this data into it's properties and this functions - into it's methods. Best example - test cases in unit test.
In both cases declaration of new interface/class is needed every time, I need to do it. With anonymous methods this could be done without wasting time on meaningless declarations, such as interface/class declarations.
So, I would like to contribute. Bad thing - I don't know structure of FPC compilator. Could somebody help me with it?
What is needed to do:
This code:
type
TRef = reference to procedure(W:Type);
TClass=class
public
Z:TType1;
function Proc(X:TType2):TRef;
end;
function TClass.Proc(X:TType2):TRef;
var Y:TType3;
begin
Y := 10;
Result := procedure(W:TType4)
begin
Z := X + Y + W;
end;
end;
Should be converted into this code:
type
TAnonymousProc = procedure(W:TType4);
IFrameInterface=interface
procedure AnonymousProc(W:TType4);
end;
TAnonymousRef = record
{Same, as for procedure/function of object, but for interface, instead of object}
{Refrence to method itself is required, as one frame object can have several anonymous methods}
Intf:IFrameInterface;
Proc:TAnonymousProc;
end;
TClass=class
public
Z:TType1;
function Proc(X:TType2):TAnonymousRef;
end;
TFrameObject = class(TInterfacedObject, IFrameInterface)
public
Object:TClass:
X:TType2;
Y:TType3;
procedure AnonymousProc(W:TType4);
end;
procedure TFrameObject.AnonymousProc(W:TType4);
begin
Object.Z := X + Y + W;
end;
function TClass.Proc(X:TType2):TAnonymousRef;
var FrameObject:TFrameObject;
begin
FrameObject:= TFrameObject.Create;
FrameObject.Object := Self;
FrameObject.X := X;
FrameObject.Y := 10;
Result.Intf := FrameObject;
Result.Proc := @TFrameObject.AnonymousProc;
end;
Also when you perform <Reference to procedure> = <Procedure of object> operation, following code should be generated:
TProcOfObject = procedure(W:TType) of object;
TRefToProc = reference to procedure(W:TType);
X:TProcOfObject;
Y:TRefToProc;
Y := X;
Should be converted into:
TProcOfObject = procedure(W:TType) of object;
TRefToProc = reference to procedure(W:TType);
X:TProcOfObject;
Y:TRefToProc;
Y := procedure(W:TType2)
begin
X(W);
end;