DIP6: Attributes

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Tue Aug 4 09:23:41 PDT 2009


Steven Schveighoffer wrote:
> On Tue, 04 Aug 2009 09:45:51 -0400, grauzone <none at example.net> wrote:
> 
>> Steven Schveighoffer wrote:
>>> don't think it's worth adding them until we can have full reflection 
>>> capabilities so we can get at elements of code and therefore get the 
>>> annotations associated with it.  I see much more usefulness for 
>>> annotations as reflection hints than as a replacement for keywords.
>>
>> But we already have full reflection. It's called __traits. You can 
>> build a serialization library or "proper" (user friendly?) reflection 
>> on top of it.
> 
> I think you are the 1 millionth person to say it, and yet we still do 
> not have a "user friendly" reflection system.  Why is that?  You'd think 
> that if it could be done, somebody would have done it by now.

The reality is there's quite few of us. D is not in the stage where if 
something could be done, somebody somewhere has done it or is working on it.

For example, I myself didn't know about __traits(allMembers) until it 
was mentioned in this group. That's why I'd defined defineEnum, which 
now is a relic replaced by the appropriate mechanism, contributed to by 
Shin Fujishiro.

I know exactly how to go about a reflection system, but I simply haven't 
gotten around to it. Here's an initial shot: starting with std.variant, 
implement a function "call":

class A { int foo() { return 42; } }
...
auto v = Variant(new A);
writeln(*v.call("foo").peek!int());

That should print 42. This is eminently doable with what we have now, 
and could then be extended to multiple arguments etc. with the 
appropriate amount of sweat.

The way to implement this would be to use __traits(allMembers) in the 
templated constructor to store a hash that maps strings to delegates. 
The delegates take no argument and return Variant. During construction 
you can figure which members can be invoked with no arguments by using 
e.g. is(typeof(...)) and initialize the hash appropriately. In the 
call() function, you look up the string and fire the delegate.


Andrei



More information about the Digitalmars-d mailing list