custom attribute proposal (yeah, another one)

Marco Leise Marco.Leise at gmx.de
Sun Apr 8 03:56:05 PDT 2012


Am Fri, 06 Apr 2012 16:53:56 +0200
schrieb Timon Gehr <timon.gehr at gmx.ch>:

> On 04/06/2012 04:23 PM, Steven Schveighoffer wrote:
> > Why should we be restricted to only structs? Or any type for that matter?
> >
> 
> A restriction to only structs is not a restriction because structs can 
> have arbitrary field types.

+1

> > The benefit to using CTFE functions is that the compiler already knows
> > how to deal with them at compile-time. i.e. less work to make the
> > compiler implement this.
> >
> 
> It is exactly the same amount of work because CTFE is able to execute 
> struct constructors.

Yep. Well, in the end the older idea of attributes == structs/classes is - as Adam D. Ruppe said - exchanging the constructor for a function call. You can do the same as with structs/classes and a little more (return basic types). IDEs can work with this proposal. And if we have to prepend @attribute to our CTFE-attribute-functions or attribute-structs that's fine, too with me. :)

While I give Steven a virtual karma point for making it clear that not "everything is an object" (or struct) with his idea, 
I prefer structs-only over functions, because we could augment these structs with compiler recognized methods/fields at a later point. Think of the range interface here, which is implicit. Some examples:

@attribute struct MyAttribute {
	// this attribute-struct is allowed multiple times on a symbol
	enum bool allowMultiple = true;

	// cannot be used on classes, but structs, methods and fields
	enum uint appliesTo = Fields | Methods | Structs;

	// Run any action in context of the filled attribute structure and 
	// the type it is applied to. With CTFE I/O, it could generate
	// binaries or text files with bindings.
	void onInvokation(T)() { … }

	void invariant() { static assert(author, "Author must be given.") }

	string author;
	string email = "no email;
}

@MyAttribute(author = "Some Name", email = "some at email")
@MyAttribute(author = "Someone Else", email = "else at email")
struct Test { … }

All of this is nice-to-have at most. I imagine it becomes interesting when attributes are offered by libraries, and you want to give the user of your attributes some validation and convenience. E.g. the compiler can guarantee that only allowMultiple-attributes appear multiple times, so you can focus on implementing the logic instead of checking for usage errors.

-- 
Marco



More information about the Digitalmars-d mailing list