custom attribute proposal (yeah, another one)

Johannes Pfau nospam at example.com
Sat Apr 7 00:10:54 PDT 2012


Am Fri, 06 Apr 2012 16:33:21 -0400
schrieb "Steven Schveighoffer" <schveiguy at yahoo.com>:

> On Fri, 06 Apr 2012 15:03:39 -0400, Piotr Szturmaj
> <bncrbme at jadamspam.pl> wrote:
> 
> > Steven Schveighoffer wrote:
> 
> >> What if I have 20 string attributes, I must define a new attribute
> >> type for each one? This seems like unneeded bloat.
> >
> > I don't see advantage of functions here, twenty of them is also a
> > bloat. Different types give you different _names_ for different
> > purposes. Those _names_ are crucial to support the attributes.
> 
> Unused function do not make it into the EXE.

But as long as you mark attribute structs in some special way
(@attribute struct Author), this can also be guaranteed for structs.
Afaik ignoring unused functions is currently done by the linker, but I
think functions/structs only used for attributes should probably never
make it to the linker. I think we already had cases were linkers didn't
strip unused functions for some reason?

Regarding code bloat: If struct initializers could be used with
attributes, a constructor isn't necessary and the minimal code is:
------
@attribute struct Author
{
    string name;
}

@Author("Johannes Pfau") int test;
or
@Author{name: "Johannes Pfau"} int test;
------

That's exactly as much code as using functions:
------
@attribute string Author(string name)
{
    return name;
}

@Author("Johannes Pfau") int test;
------


I don't have a strong opinion whether storable types should be limited
to structs, but I think classes add little benefit and complicate
things because of inheritance (at least if you query attributes by
type). What we want to do here is store _data_ and the D style is to
use structs for pure data. Basic types could be useful too but when
querying by type, those can't work well.


BTW: I think there's one thing both your and my proposals are missing:

The function/constructor returning the data must be pure: We can't
guarantee this function will be executed only once, but the value of
the attribute should always be the same. Consider this scenario:

a.d
----
@RandomNumber() int test;
----

b.d
---
auto value1 = __traits(getAttribute, a.test, RandomNumber);
---

c.d
---
auto value2 = __traits(getAttribute, a.test, RandomNumber);
---

All files are compiled individually. Now the compiler has to call
RandomNumber() 2 times: one time for b.d and one time for c.d, but
value1 should be the same as value2.




More information about the Digitalmars-d mailing list