User Defined Attributes

Jacob Carlborg doob at me.com
Wed Nov 14 02:53:41 PST 2012


On 2012-11-14 08:46, Walter Bright wrote:

> We agree that strings can be used globally as attributes with different
> meanings, right?

Yes, but I would consider that a bad idea.

> So why can't test.foo.bar also be used globally as an attribute with
> different meanings? It's just a type name, it has no magic property that
> says it cannot be used for different purposes.

I guess it could. But there is no way of preventing the user from doing 
stupid things. I can create a map container out of two arrays, but 
that's not how arrays are intended to be used.

> Ok, let's call it:
>
>      std.mytypes.mystring
>
> ? Now have those string contents mean different things to different
> users of std.mytypes.mystring.

If "std.mytypes.mystring" is a variable of the type "string" then the 
fully qualified name is lost if it's used as an attribute. Something 
like this:

[std.mytypes.mystring] int a;

pragma(msg, __traits(getAttributes, a).stringof);

Would result in:

("foo")

pragma(msg, typeof(__traits(getAttributes, a)).stringof);

Would result in:

(string)

The name "std.mytypes.mystring" is gone. You have no idea where the 
string came from, who could have put it there. You would need to put the 
fully qualified name in the content of the string:

module std.mytypes;

string mystring = "std.mytypes.mystring";

The whole problem with this is that there is no actual thing called 
"attribute", there are just symbols with attached values.

In most cases I think it's the symbol/type name that is interesting. I 
imagine many attributes just look like this:

@attribute struct Serializable {}

I would prefer that only user defined types explicitly marked with 
@attribute (or similar) could be used as attributes. And preferably, 
that they cannot be used for anything else.

If only user defined types (and preferably marked with @attribute) are 
allowed then you can know exactly where a given attribute comes from and 
you can look up the documentation. Sure you cannot prevent anyone from 
using the attribute with a different meaning then it was intended for. 
But that's true for many other things in programming as well.

-- 
/Jacob Carlborg


More information about the Digitalmars-d-announce mailing list