Multiple alias this and alias this in classes

Timon Gehr timon.gehr at gmx.ch
Tue Jan 17 00:31:44 UTC 2023


On 1/17/23 00:27, deadalnix wrote:
> 
> On an asside, I implemented both multiple alias this and alias this for 
> classes in SDC. Because these feature were never completed in DMD, I had 
> to extrapolate to figure out what the semantic should be, and this is 
> what I came up with.
> 
> 1/ Alias this is used in two contextes: casts and identifier resolution.
> 2/ For struct, it just follow the expected rule for cast and resolution, 
> if these rule succeed, then nothing more happen. If they fail, then the 
> operation is repeated again with all the declared alias this. If the 
> number of valid result is 1 and exactly 1, then it is used. If the 
> number of valid result is 0 or greater than 1, then an error is emitted.
> 3/ For classes, lookups ignore alias this and walk up the parent stack, 
> still ignoring any alias this. If that fails, then all the alias this 
> from this class and its parent are run at once, and if the number of 
> valid result is 1, then this is fine, if it is 0 or greater than 1, then 
> an error is emitted. The same is done for casts.
> 
> I think this semantic is reasonable. But I have to say I did not put a 
> ton of though into it, so maybe there is a big fatal flaw I'm overlooking.

No, this is how it should work. I guess those rules are inspired by how 
multiple imports/mixins work in D. It's a solved problem.

It's debatable whether one should treat inheritance like just another 
alias this for lookup (I have a slight preference for that). With your 
rules it's possible to hijack an alias this lookup on a child class with 
a new base class member. However, both ways to do it are defensible I think.


Another thing you have not shown is how the lookup itself proceeds. One 
has to be careful to not run into loops there.

There is another issue for lookups that is maybe less obvious:

struct S(ulong x){
     mixin(`enum has`~text(x)~`=2;`);
     auto get()(){ return S!(x+1)(); }
     alias get this;
}

void main(){
     S!0 s;
     writeln(s.has500);
     static assert(!is(typeof(s.has501)));
}

I.e., there may be an unbounded number of nested alias this. As you can 
see above, DMD seems to just limit the number of alias this expansions 
to 500. For multiple alias this, you probably also want to specify a 
reasonable search order, such that not too many irrelevant templates get 
instantiated just to find something at a low depth.



More information about the Digitalmars-d mailing list