February 16

I want to get a reference to a parent function from inside a nested function. I need it for getUDAs!(parentFunction, attribute).

__traits(parent, mixin(__FUNCTION__)) works inside the parent function and gives me the module, but mixin(__FUNCTION__) alone inside the nested function immediately errors.

module foo;

void bar(string s, int i)
{
    assert(__FUNCTION__ == "foo.bar");
    alias parentModule = __traits(parent, mixin(__FUNCTION__));
    assert(is(parentModule == module));

    void dg()
    {
        assert(__FUNCTION__ == "foo.bar.dg");
        alias parentFunction = __traits(parent, mixin(__FUNCTION__));
    }
}

void main() {}
onlineapp.d(12): Error: function `bar` is not callable using argument types `()`
onlineapp.d(12):        too few arguments, expected 2, got 0
onlineapp.d(3):        `foo.bar(string s, int i)` declared here

So mixin(__FUNCTION__) seems to be trying to call the parent function rather than giving me the symbol of the nested one, like foo.bar().dg. I tried making it mixin("&" ~ __FUNCTION__) but it did not help.

How can I make this work?

February 16

On Sunday, 16 February 2025 at 07:38:09 UTC, Anonymouse wrote:

>

How can I make this work?

As a workaround, you can define a useless symbol and get the parent of that.

module foo;

void bar(string s, int i)
{
    assert(__FUNCTION__ == "foo.bar");
    alias parentModule = __traits(parent, mixin(__FUNCTION__));
    assert(is(parentModule == module));

    void dg()
    {
        assert(__FUNCTION__ == "foo.bar.dg");
	enum n = 0;
        alias parentFunction = __traits(parent, __traits(parent, n));
	pragma(msg, __traits(identifier, parentFunction)); // bar
	pragma(msg, __traits(identifier, __traits(parent, n))); // dg

    }
}

void main() {}