Proposal: user defined attributes

Jacob Carlborg doob at me.com
Sat Mar 17 09:12:12 PDT 2012


On 2012-03-16 14:35, Adam D. Ruppe wrote:
> On the ride over here today, I had a thought that
> I think neatly solves the user defined attribute
> question.

I would love to have user defined attributes in D but I'm not completely 
like your approach. I would go with something more like Java 
annotations. This is how I would like user defined attributes to work.

Attributes can be applied to most declarations like: classes, fields, 
variables, functions, parameters and so on. Attributes are used with the 
following syntax:

@foo(key = "value", key2 = "value2) class Bar {}

"foo" is the name of the attribute. In the parentheses is a key-value 
list passed to the attribute. The values can be of any type available at 
compile time.

Attributes are defined as follows:

We add a new attribute called "@annotation" or "@attribute". This 
attribute is applied to a class or struct to make it an attribute:

@attribute class foo
{
     string key;
     string key2;
}

The keys the attribute accepts are declared in the class as either 
fields or methods (haven't decided yet). It's perfectly fine to have an 
attribute accepting no values which doesn't have to declare any keys:

@attribute class bar {}

If an attribute only accepts one value the name of the value needs to be 
"value":

@attribute class fooBar
{
     string value;
}

This allows to not have to specify the key when passing a value to the 
attribute:

@fooBar("asd") class Foo {}

Accessing information about attribute should be possible both during 
compile time and runtime. At compile time "__traits" can be used:

__traits(hasAttribute, bar, Foo); // returns true if the attribute "bar" 
as been applied to "Foo"

__traits(getAttribute, bar, key, Foo); // returns the value of the key "key"

This is all very similar to how it works in Java:

http://docs.oracle.com/javase/1.5.0/docs/guide/language/annotations.html

-- 
/Jacob Carlborg


More information about the Digitalmars-d mailing list