User Defined Attributes

Gor Gyolchanyan gor.f.gyolchanyan at gmail.com
Tue Nov 6 06:23:53 PST 2012


On Tuesday, 6 November 2012 at 14:05:46 UTC, Adam D. Ruppe wrote:
> On Tuesday, 6 November 2012 at 13:55:49 UTC, Rory McGuire wrote:
>> You can put the attribute on the function.
>
> Yeah, but that's an awfully roundabout way to add an attribute 
> to the parameter...
>
> if it went on func params:
> void foo([Hint("this does something")] string something) {}
>
> otherwise we'd have to do something like
>
> [ParamHint("something", "this does something")] void foo(string 
> something) {}
>
>
> Which isn't really ahead from the old hack of
>
> enum attr_foo_someting = Hint("");
>
> and has similar problems in matching names. It's a little 
> better but not as good as it could be.

What if the data in the attribute needs to be specific to the 
symbol on which the attribute is set on? Can you query the symbol 
from inside the attribute?
What if the attribute needs to change the symbol being defined?
For instance (using commonly desired syntax):

@flags enum A { ... }

the "flags" attribute would replace the declaraction of A with 
another enum declaration with the same name and same members, but 
with replaced initialization and would static assert(false, 
"flags enum can't have initializers") if any initializers are 
given.

The existing "[data] declaration" is one thing. It adds 
compile-time data to symbols, which is very very important, but 
it's not the only thing that is needed. What I described above is 
not quite an attribute, but an annotation. The semantics of 
attributes as Walter made them is perfect. The annotation should 
be  defined like so:

template myAnnotation(alias symbol, annot_args...)
{
     // ...
     ["myAnnoration adds this attribute"] alias symbol 
myAnnotation; // or alias anything else if a change in necessary.
}

@myAnnotation(arg1, arg2, arg3) class Declaration
{
}

here the "symbol" is passed to the template as the first 
parameter and the parameters in the parentheses are passes after 
it. It's basically a thin syntactic sugar over some manual (and 
very ugly) manual template instantiations (and mixins), so it 
doesn't add anything new.

Annotations then become a way to statically replace declarations.
This would be perfect to replace

Scoped!MyClass mc;

with:

@scoped MyClass mc;

Which looks quite like a very beautiful built-in syntax, but is 
actually a library solution.

IMHO, Attributes as they are should stay, but annotations should 
be added.

P.S. Thank you, Walter very very much for making attributes!!! :-)


More information about the Digitalmars-d-announce mailing list