4 ms·
(Grumpy old man edit: __VA_OPT__ has been implemented in macro libraries by users for decades without language support. Making it a keyword made no more sense t
by foundry27 3y ago
(Grumpy old man edit: __VA_OPT__ has been implemented in macro libraries by users for decades without language support. Making it a keyword made no more sense to me than if vector was made a language primitive in C++)
Tree-based expansion machines are the usual way to do preprocessor recursion for non-trivial applications (see: order-pp, chaos-pp). They have that desirable property of letting you process an exponential number of tokens using a linear number of macros, while letting you “bail out” at any time and avoid needing to resolve all of those deeply-nested macro expansions when there isn’t more work to be done.
Getting the linear->exponential property is actually the easy part, since you just need two parallel hierarchies of macros (shamelessly plugging https:.//github.com/notfoundry/pp2/blob/master/include/pp2/machine/vm.h as the most readable implementation). It’s how you stop expanding before the heat death of the universe once you have an effectively unlimited number of recursive expansions available that’s really interesting: if you design all of your recursive macros to return their output wrapped in parentheses, you can write your recursion machine in such a way that at the end of every recursion step, those parentheses are used to complete a function-like macro expansion to get to each next recursion step downstream. When you want to stop computation, you make your recursive macro stop expanding to something parenthesized, and the system naturally stops making progress. In a sense, each recursive macro provide its own potential energy to power the whole recursion system!