Proposal: user defined attributes

Adam D. Ruppe destructionator at gmail.com
Wed Mar 21 10:26:18 PDT 2012


On Wednesday, 21 March 2012 at 16:02:22 UTC, Andrei Alexandrescu 
wrote:
> Ideally the above should work, and also mixing in several 
> NonSerialized instances within the same type should also work.


Oh god, I feel like the spawn of Hacktan.

I'm taking the DSL identifiers to the max. Consider
the following:

http://arsdnet.net/dcode/omg.d


Bottom line:

struct A {
         int a;
         int b;
         mixin Note!(a, q{ "NonSerialized" });
         mixin Note!(a, q{ "Awesome" });
         mixin Note!(b, q{ "Filthy Hack" });
}

void main() {
         pragma(msg, getNotes!(A.a));
}

$ dmd omg.d
["NotSerialized", "Awesome"]



How does it work?



What it does is for each note, it creates a dummy
enum.

The enum's name is a D expression, encoded as a
valid identifier. This expression is a ~= op here.

The struct looks like this:

struct A{
   int a;
   int b;
   enum _attr_mixin_a_32_4c_NonSerialized;
   enum _attr_mixin_a_32_4c_Awesome;
   enum _attr_mixin_b_32_4c_Filthy_32_Hack;
}


getNotes looks for this pattern, decodes it,
and then mixes in the expression:

string[] notes;
if(identifier is the right item)
mixin("notes " ~ decoded_identifier);

return notes;




So, it embeds D code to rebuild the requested
data as the names of identifiers.

We run it every time we want to get it.



Note that everything I said in my long post still
applies here. Like I said before, we *can* make it
work, but it comes with a lot of baggage that hurts
maintainability and interop with third party code.

Remember, you have to add code to your library just
to *ignore* these attributes.

You can't just ignore them, no, you have to add special
code to skip them.

That's no good. This also has duplicated names and the
other problems mentioned before with overloading,
inheritance and more.


The compiler keeping a list of notes attached to the
declaration remains the only *right* way to do it. That
it is slightly prettier is an added benefit, but not the
main reason why we need it there.


More information about the Digitalmars-d mailing list