Proposal: user defined attributes

Adam D. Ruppe destructionator at gmail.com
Tue Mar 20 17:35:46 PDT 2012


On Wednesday, 21 March 2012 at 00:03:28 UTC, James Miller wrote:
> template hasAnnotation(alias data, string an) {
>     enum hasAnnotation = __traits(hasAnnotation, data, an);
> }

I'm actually thinking of identifying them by type. Types
are well established in the language - scoping, namespaces,
fields, and so on are all solved.

Querying them is solved too - we can look over a TypeTuple
and use is(typeof()) to get what we want.

(using types as names instead of strings is the idea that
came to me on my ride that prompted this thread - it is the
missing piece in what I wanted here. Strings can conflict,
but types already handle this.)


So you'd just very simply do:

struct MyAttribute { bool activated; }

// @note is just like doing internalTuple ~= MyAttribute(true)
// and MyAttribute is of course just a plain old struct
initializer
@note(MyAttribute(true)) int a;

To check it:

foreach(note; __traits(getNotes, member_a))
      static if(is(typeof(note) == MyAttribute) {
          // do what you want here, ignore types you don't know
      }


Of course, this is in a plain template. No implicit
stuff, no modifying the ast. This data only comes up
when you ask for it, and you ask for it in a plain
old mixin template or something like that - existing
language features.

> How far do notes extend?

I'd only put it on declarations (variables,
classes, structs, enums, members, and function
parameters.)

> What data can be packed into annotations?

Being able to use custom types is an
important part of my idea here.


More information about the Digitalmars-d mailing list