nielsAD / lape

Scripting engine with Pascal-like syntax for FPC and Delphi
119 stars 28 forks source link

Add memory management operators (AddRef & Finalize) #146

Closed ollydev closed 3 years ago

ollydev commented 4 years ago

Added class operators AddRef and Finalize. The user must implement their own refcounting if needed:

type
  TManagedRecord = record
    MyObject: Int32;
    Ref: ^Int32;
  end;

class operator TManagedRecord.AddRef(var Obj: TManagedRecord);
begin
  Assert(Obj.Ref <> nil);

  Obj.Ref^ += 1;
end;

class operator TManagedRecord.Finalize(var Obj: TManagedRecord);
var
  i: Int32;
begin
  Assert(Obj.Ref <> nil);
  Assert(Obj.Ref^ > 0);

  Dec(Obj.Ref^);
  if (Obj.Ref^ > 0) then
    Exit;

  // Free stuff here!

  FreeMem(Obj.Ref);
end;

function GetManagedRecord: TManagedRecord;
begin
  Result.MyObject := 123;
  Result.Ref := GetMem(SizeOf(Int32));
  Result.Ref^ := 1;
end;

Perhaps in the future an magic record can be added to inherit from which would do the refcounting internally?


Most of the work is on in TLapeTree_Operator.Compile when assigning:

Other changes:

slackydev commented 4 years ago

Cool

ollydev commented 3 years ago

Will be reworked.