RomanYankovsky / DelphiAST

Abstract syntax tree builder for Delphi
Mozilla Public License 2.0
271 stars 116 forks source link

SyntaxNodeNames should be automatically derived from SyntaxNode types. #232

Open JBontes opened 6 years ago

JBontes commented 6 years ago

We can easily do this with a bit of trickery using a record, so the constant array stays a constant. This will make sure that SyntaxNodeNames are always in sync.

Here's the fix:

type
  SyntaxNodeNames = class
  strict private
    class var FData: array[TSyntaxNodeType] of string;
    class function GetItem(const index: TSyntaxNodeType): string; inline;
    class constructor Init;
  public
    class property Items[const index: TSyntaxNodeType]: string read GetItem; default;
  end;

implementation

uses
  SysUtils, TypInfo;

{ TSyntaxNodeNames }

class function SyntaxNodeNames.GetItem(const index: TSyntaxNodeType): string;
begin
  Result:= FData[index];
end;

class constructor SyntaxNodeNames.Init;
var
  value: TSyntaxNodeType;
begin
  for value := Low(TSyntaxNodeType) to High(TSyntaxNodeType) do
    FData[value] := Copy(LowerCase(GetEnumName(TypeInfo(TSyntaxNodeType), Ord(value))), 3);
end;