DIP6: Attributes

grauzone none at example.net
Sun Aug 2 21:02:23 PDT 2009


Ary Borenszweig wrote:
> http://www.prowiki.org/wiki4d/wiki.cgi?LanguageDevel/DIPs/DIP6

The next step would be to introduce user defined annotations. I propose 
this:

//--------------

//declaring a user defined annotation type
@annotation
struct MyAnnotation {
     int x;
     char[] y;
     SubAnnotation sub;
}
struct SubAnnotation {
     int x;
}

//use the annotation on SomeType
@MyAnnotation(123, "456", SubAnnotation(789))
class SomeType {
}

//reading user defined annotations
void foo() {
     foreach (t; __traits(getAnnotations, SomeType) {
         //t is a value of the annotation type
         //SomeType is only annotated with MyAnnotation
         static assert(is(typeof(t) == MyAnnotation));
         //can read out the annotation values
         assert(t.y == "456");
     }
}
//--------------


Using @annotation on a type introduces the type name into the annotation 
namespace. This means the type can be used as annotation on other types.

The annotation declaration is parsed as if you'd define a compile time 
constant using the expression following the @, e.g. "const c = 
MyAnnotation(123, [...]);"
This means the @ is actually just followed by an expression, that 
actually uses opCall() (in this case opCall is autogenerated by the 
compiler). The expression is evaluated using CTFE.

Note that compile time annotations (like @override, @property) still can 
collide with user defined types, but only if those types are marked by 
@annotation. (Actually, compile time annotations can be normal types 
declared in object.d.)

__traits(getAnnotations, SomeType) returns a tuple containing the values 
of all annotations applied to a type. In other words, the result of the 
CTFE execution of each annotation.


Any thoughts?

PS: I wouldn't use annotations for all attribute keywords (like 
override, final, pure, ...). Some keywords should be left as they are. 
Only seldom used and/or new keywords should be introduced as annotations 
(for example deprecated or __gshared [there's a type on the DIP page btw.]).

PPS: shoudl annotations follow the normal D attribute syntax? E.g. allow 
this:
@someannotation declaration;
@someannotation {
     declaration1;
     declaration2;
}
@someannotation:
     declaration1;
     declaration2;



More information about the Digitalmars-d mailing list