"spirit" like template parser generator in 100 Lines of code (almost)

Don Clugston dac at nospam.com.au
Tue Dec 19 04:43:47 PST 2006


BCS wrote:
> -- The parameter on a foreach isn't const. --
> Actual this doesn't stop anything from working, it just makes some 
> things more difficult.
> 
> foreach(i;TupleMaker!())
>  Template!(i)();
> 
> becomes:
> 
> alias TupleMaker!() tempTuple
> foreach(j,_;tempTuple)
> {
>  const i = tempTuple[j];
>  Template!()();
> }
> 
> This is not a trivial complaint. While I was working on my BigNum 
> template I noticed that the const variable adds ops to the function even 
> with the -O flag.

Another alternative workaround is this:
-------
template countTo(int a, A...)
{
     static if (a==0) alias A countTo;
     else static if (a&1) alias countTo!(a-1, void, A) countTo;
     else alias countTo!(a/2, A, A) countTo;
}

foreach(j,_; countTo!(tempTuple.length)) {
   const i = tempTuple[j];
}
In fact, if you can calculate the value of 'i' based only on 'j', this 
can be a much more general solution, for example for your Bignum 
template. It is very quick, can cope with numbers as high as 20000 or 
so, and doesn't generate any runtime code (in fact, it can't, because 
there's nothing you can do with a tuple of 20000 voids, except count it).
It works well for cases like:

foreach(i,_; countTo!(s.length)) {
   static if (s[i]=='+') { ... }
   ...
}
allowing you to iterate over the contents of a string.
There are some pretty cool things that work here -- you can add labels 
in one iteration, and generate goto statements (or asm jmp instructions) 
in a different iteration. I don't know how that works, but it's awesome 
because it lets you turn a compile-time string into a run-time state 
machine...



More information about the Digitalmars-d-announce mailing list