Interesting question! You can declare attributes on almost anything, the problem is retrieving them using RTTI. Here’s a quick console demo of declaring custom attributes for:
- Enums
- Function type
- Procedure type
- Method type (
of object) - Aliased type
- Record type
- Class type
- Record type that’s internal to a class
- Record field
- Record method
- Class instance field
- Class
classfield (class var) - Class method
- Global variable
- Global function
- Local variable
Didn’t find a way to declare a custom attribute for a property of a class. But a custom attribute can be attached to the getter or setter methods.
Code, the story continues after the code:
program Project25;
{$APPTYPE CONSOLE}
uses
Rtti;
type
TestAttribute = class(TCustomAttribute);
[TestAttribute] TEnum = (first, second, third);
[TestAttribute] TFunc = function: Integer;
[TestAttribute] TEvent = procedure of object;
[TestAttribute] AliasInteger = Integer;
[TestAttribute] ARecord = record
x:Integer;
[TestAttribute] RecordField: Integer;
[TestAttribute] procedure DummyProc;
end;
[TestAttribute] AClass = class
strict private
type [TestAttribute] InnerType = record y:Integer; end;
private
[TestAttribute]
function GetTest: Integer;
public
[TestAttribute] x: Integer;
[TestAttribute] class var z: Integer;
// Can't find a way to declare attribute for property!
property Test:Integer read GetTest;
[TestAttribute] class function ClassFuncTest:Integer;
end;
var [TestAttribute] GlobalVar: Integer;
[TestAttribute]
procedure GlobalFunction;
var [TestAttribute] LocalVar: Integer;
begin
end;
{ ARecord }
procedure ARecord.DummyProc;
begin
end;
{ AClass }
class function AClass.ClassFuncTest: Integer;
begin
end;
function AClass.GetTest: Integer;
begin
end;
begin
end.
The trouble is retrieving those custom attributes. Looking at the rtti.pas unit, custom attributes can be retrieved for:
- Record type (
TRttiRecordType) - Instance type (
TRttiInstanceType) - Method type (
TRttiMethodType) - Pointer type (
TRttiPointerType) – what’s that used for? - Procedure type (
TRttiProcedureType)
There’s no way of retrieving any sort of RTTI for “unit” level or local variables and procedures, hence no way of retrieving information about attributes.