What are AST Macros?
David Bennett
davidbennett at bravevision.com
Sat Apr 14 02:45:38 UTC 2018
On Friday, 13 April 2018 at 11:54:12 UTC, David Bennett wrote:
> Also the other idea I had was to have mixin functions that only
> take compiletime args (they are UFCS-able though, unlike
> templates) and mixin themselves when called like:
>
> ---
> mixin add1Xtimes(alias int a, alias int t){
> uint i=t;
> do{a++;}while(--i);
> return a;
> }
> @safe unittest{
> uint n=0;
> n.add1Xtimes!(4).add1Xtimes!(6);
> assert(n==10);
> }
> ---
>
> [snip]
>
> I haven't really given much thought to the implementation of
> this though.
With more thought thats probably not a good solution as its
different from the rest of the language and would be harder then
it needs to be in order to integrate with the front-end.
What could work though is having a new AutoMixinDecloration that
was inited with an expression. This expression would contain a
call chain to regular functions, templates, other
AutoMixinDecloration etc. Then when it's called it dups the
contents of these functions into the callers scope.
---
auto ref incXTimesAndCount(string cident, alias uint csym, uint
times)(auto ref uint a=0){
uint t = times;
do{
mixin(cident~"++;");
csym++;
a++;
}while(--t);
return a;
}
auto mixin incXAndXTimesAndCount(string cident, alias uint csym,
uint t1, uint t2)
= incXTimesAndCount!(cident, csym,
t1).incXTimesAndCount!(cident, csym, t2);
@safe unittest{
uint n=10;
uint c1=0;
uint c2=0;
uint r = n.incXAndXTimesAndCount!("c1", c2, 4, 6);
assert(n==20);
assert(c1==10);
assert(c2==10);
assert(r==20);
}
---
And it lowers to this in the front end:
---
@safe unittest{
uint n=10;
uint c1=0;
uint c2=0;
uint __m0_t=4;
do{n++; c1++; c2++;}while(--__m0_t);
uint __m1_t=6;
do{n++; c1++; c2++;}while(--__m1_t);
uint r = n;
assert(n==20);
assert(c1==10);
assert(c2==10);
assert(r==20);
}
---
Or it might be even possible to make the current
TemplateMixinDeclaration to act like this if you add the auto
keyword to the declaration with a symbol with the same name in
the scope and the above was just sugar to this:
---
auto mixin template incXAndXTimesAndCount(string cident, alias
uint csym, uint t1, uint t2)
{
alias incXAndXTimesAndCount
= incXTimesAndCount!(cident, csym,
t1).incXTimesAndCount!(cident, csym, t2);
}
---
More information about the Digitalmars-d
mailing list