Idea: Context sensitive attribute functions.

Jonathan M Davis newsgroup.d at jmdavisprog.com
Tue Jun 19 22:49:28 UTC 2018


On Tuesday, June 19, 2018 22:22:23 Dennis via Digitalmars-d wrote:
> On Tuesday, 19 June 2018 at 21:38:14 UTC, Jonathan M Davis wrote:
> > Attribute inference is all about inferring the attributes of
> > the templated function based on its implementation, not
> > adjusting its implementation based on where it's used.
>
> Indeed, I realised that the same template instantiation can't
> possibly have both a @nogc and @gc version, so there has to be a
> template parameter. You can automatically set one however:
>
>
> ```
> void main() @nogc {
>      example();
> }
>
> void example(string callee = __FUNCTION__)() {
>
>      int a = 8;
>      static if (isNoGc!callee) {
>          printf("printf %d", a);
>      } else {
>          writefln("writeln %d", a);
>      }
> }
>
> bool isNoGc(string functionName)() {
>      import std.algorithm;
>      mixin(`return [__traits(getFunctionAttributes,
> `~functionName~`)].canFind("@nogc");`);
> }
> ```
>
> This seems to work. I'm not sure how robust it is though. You
> might need an extra `mixin("import "~functionName~";");` in
> `isNoGc` when it's called from other modules (if that helps at
> all).

Hmm. That's clever, but that approach would not work very well with function
overloads. Also, it falls apart on some level if the caller is a template
function that relies on attribute inference to be @nogc. In such cases, the
caller would be infered as not being @nogc, and example would be compiled
with the GC version. In addition, even if it all worked perfectly, it would
mean compiling a different instantation of the function for every function
that calls it, which seems likely to cause an awful lot of bloat. It's not
as bad as using __FILE__ and __LINE__ as template arguments, but it's close.

Another problem here is that as long as we can't introspect on private
members of other modules (which really should be fixed), this would likely
fail to compile when the caller is private and in another module. But
hopefully, that's just a temporary issue. Making it deal with overloads
correctly is likely a far bigger issue long term.

- Jonathan M Davis



More information about the Digitalmars-d mailing list