DIP6: Attributes

yigal chripun yigal100 at gmail.com
Mon Aug 3 01:03:48 PDT 2009


grauzone Wrote:

> 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;

this is a good start but as already noted by others, you can't specify types with structs. we also can't use type tuples cause of the auto flatten behavior. 

the type tuple issue needs to be fixed and perhaps we can introduce type variables. something like:
type t = int; 

other thoughts on the subject:
the user should be able to specify the lifetime of the annotations, compile-time vs. run-time. 




More information about the Digitalmars-d mailing list