Author Topic: Record Composition  (Read 581 times)

mattias

  • Administrator
  • Full Member
  • *
  • Posts: 226
    • http://www.lazarus.freepascal.org
Record Composition
« on: October 19, 2026, 11:45:26 am »
Thanks to Frederic Kehrein FPC main now supports Record Composition:

A record can now "contain" another record and have that record's members appear as its own.
Firstly this allows easy and automated conversion of C code, which uses anonymous structs and unions introduced in C11, into Pascal and to use C libraries frictionless and transparently through the same types and interfaces.
Secondly it allows for non trailing and multiple variant parts.
And last but not least it can avoid {$IFDef} structures within the record definition allowing to reuse existing types.

The feature is enabled with {$modeswitch RecordComposition}
It is not part of any mode by default.

Example:

Code: Pascal  [Select][+][-]
  1. program demo;
  2. {$mode objfpc}{$H+}
  3. {$modeswitch advancedrecords}
  4. {$modeswitch recordcomposition}
  5. type
  6.   TPoint = record
  7.     X, Y: Integer;
  8.     procedure Offset(dx, dy: Integer);
  9.   end;
  10.  
  11.   TSize = record
  12.     Width, Height: Integer;
  13.     function Area: Integer;
  14.   end;
  15.  
  16.   TRectangle = record
  17.     contains TopLeft: TPoint;  // named composition
  18.     contains TSize;            // unnamed composition
  19.     function Right: Integer;
  20.   end;
  21.  
  22. procedure TPoint.Offset(dx, dy: Integer);
  23. begin
  24.   Inc(X, dx);
  25.   Inc(Y, dy);
  26. end;
  27.  
  28. function TSize.Area: Integer;
  29. begin
  30.   Result := Width * Height;
  31. end;
  32.  
  33. function TRectangle.Right: Integer;
  34. begin
  35.   Result := X + Width;   // composed members, no qualifier needed
  36. end;
  37.  
  38. var
  39.   r: TRectangle;
  40. begin
  41.   r.X := 10;             // same as r.TopLeft.X
  42.   r.Y := 20;
  43.   r.Width := 300;
  44.   r.Height := 200;
  45.   r.Offset(5, 5);        // calls TPoint.Offset with Self = r.TopLeft
  46.   WriteLn(r.TopLeft.X, ' ', r.Right, ' ', r.Area);  // 15 315 60000
  47. end.
  48.  


See here for the more information:
https://wiki.freepascal.org/FPC_New_Features_Trunk#Record_Composition

AlexTP

  • Hero Member
  • *****
  • Posts: 2771
    • UVviewsoft
Re: Record Composition
« Reply #1 on: October 19, 2026, 08:42:28 pm »
Thank you very much (and to original author Frederic), very interesting feature.

Zoran

  • Hero Member
  • *****
  • Posts: 1999
    • http://wiki.lazarus.freepascal.org/User:Zoran
Re: Record Composition
« Reply #2 on: October 20, 2026, 05:54:26 pm »
It is originally announced (here).
I understand and agree that it needs to be announced here, inside the FPC announcement part of our forum, I just want to put here the link to the original announcement, made by the author.
Swan, ZX Spectrum emulator https://github.com/zoran-vucenovic/swan

 

TinyPortal © 2005-2018