compile time 'address'

Steven Schveighoffer schveiguy at gmail.com
Thu Nov 29 23:25:28 UTC 2018


On 11/29/18 5:56 PM, Dominic Jones wrote:
> On Thursday, 29 November 2018 at 18:49:27 UTC, Steven Schveighoffer wrote:
> 
>> Ah, ok. Essentially you are looking for the layout of the local 
>> variables.
>>
>> One thing that is available for D is the compile-time property 
>> offsetof, which gives the offset from the start of an aggregate that 
>> an item is.
>>
>> for example:
>>
>> struct S
>> {
>>   int x;
>>   bool y;
>> }
>>
>> static assert(S.y.offsetof == 4);
>>
>> So while this isn't available for function locals, the idea is 
>> similar. But I don't think there's an equivalent to what you are able 
>> to do here in C++.
>>
>> I don't think it would be a huge stretch to apply this same property 
>> to function locals, but it would require an enhancement request.
> 
> 
> This is an interesting idea.
> 
> Somehow it would be helpful to access the frame pointer, too, from the 
> variable. Obtaining this offset via the variable would enable 
> disambiguation between variables with the same local offset but from 
> different functions.

Hm... the offsetof feature would break down there. But perhaps a frame 
(or probably __traits call) could provide the function symbol, so you 
could do:

static assert(t.frame is u.frame);

Strawman could be __traits(getAggregate, sym) => symbol that contains 
sym, be it a function or struct or whatever.

> 
> 
> The example would then read something like:
> 
> auto cmp(T, U)(const ref T t, const ref U u)
> {
>    // i.e.
>    //   t.frame.offsetof := &main;
>    //   t.offsetof := main.c0.offsetof;
> 
>    enum f = t.frame.offsetof == u.frame.offsetof;
>    enum v = t.offsetof == u.offsetof;
>    return f && v;
> }
> 
> void main()
> {
>    auto c0 = 1;
>    auto c1 = 2;
> 
>    static assert(cmp(c0, c0));
>    static assert(!cmp(c0, c1));
> }
> 

I was thinking you'd do it with D compile time features:

bool cmp(alias var1, alias var2) = var1.offsetof == var2.offsetof;

struct S
{
    int x;
    int y;
}

// this actually works today:
static assert(cmp!(S.x, S.x));
static assert(!cmp!(S.x, S.y));

void main()
{
    auto c0 = 1;
    auto c1 = 2;

    // proposed
    static assert(cmp!(c0, c0));
    static assert(!cmp!(c0, c1));
}

-Steve


More information about the Digitalmars-d mailing list