Idea for @annotations

KennyTM~ kennytm at gmail.com
Mon Aug 1 00:00:44 PDT 2011


On Aug 1, 11 13:42, %u wrote:
> An idea for a potential use of annotations:
>
> How about being able to annotate _anything_ with a template?
>
> It would be the equivalent of Python's annotations: the template's
> first parameter would be an alias to the thing being annotated, and
> its return value would be the code generated for that element. Of
> course, if there's no transformation being done, then it should
> simply "return" the alias itself.
>

+1.

> This would allow you to say something like:
>
> auto memoize(alias Fn, T...)(T args) { /* memoize code here */ }
>
> @memoize
> int fib(int n) { ... }
>
> which would be somewhat (but not completely) "equivalent" to
>
> mixin memoize!(function int(int n) { ... });
>

I believe you mean

     alias memoize!(<that function>) fib;

your @property below won't work as a mixin.

Also, self-reference should be handled:

     @memoize
     ulong fib(ulong n) {
        return n < 2 ? 1 : fib(n - 2) + fib(n - 1);
     //                    ^^^ recursion^^^
     }

     @exportName("F/List")
     class F_List {
        int content;
        F_List next;
     // ^^^^^^ self-reference
     }

This works in Python trivially because functions and classes are 
looked-up by name in runtime. This isn't true in D, at least if it's a 
simple alias-ing.

>
> And more trivial things like @property would simply be
> template property(alias A) { alias A property; }
> with their sole effect being extra information found with
> reflection.
>

I'd prefer to make it more explicit, e.g. use a __traits to include that 
extra information:

     alias __traits(setAnnotation, X, "foo.prop", 1234) Y;
     // Y is a copy or reference of X but with the extra property

     enum prop = __traits(getAnnotationy, Y, "foo.prop");
     // returns 1234, compile-time error if 'foo.prop' does not exist.

     enum prop = __traits(getAnnotationy, Y, "foo.bar", false);
     // same as above but with a default value.

     static if (__traits(hasAnnotation, Y, "foo.prop"))
         alias __traits(removeAnnotation, Y, "foo.prop") Z;

So, e.g. one could write

     template serializable(alias F) if (is(f == struct) || ...) {
         alias __traits(setAnnotation, F, "mymodule.serializable", true) 
serializable;
     }

     ...

     @serializable
     struct MyObject {
        int x;
        ...
     }

and the serializer can check with

     auto serialize(F)(F x) if (__traits(getAnnotation, F, 
"mymodule.serializable", false)) {
        ...
     }

>
> Implementing this would obviously be difficult as I would assume,
> but does it sound like a reasonable idea?

Would you mind to write a DIP? 
(http://www.prowiki.org/wiki4d/wiki.cgi?LanguageDevel/DIPs)

(Speaking of which, what happened to DIP11?)


More information about the Digitalmars-d mailing list