c++macrosdsl

mutliple definition of preproccessor # value


I'm creating a project where I try to make a new language making macros.

The thing is that a macro named X is used for 2 different usages:

  1. to close a function call with parethesis like );}, where ; ends the line of code, and } closes the block of code,

  2. and sometimes I want just to ;}.

In conclusion, I need to make a smart trick where sometimes the preproccessor line after line understands X needs to be either );} or ;}.

Can I somehow do it with if else statement, or somehow to strip the if needed?

I tried some implementation of conditional value where , ( condition ? state1 : state2 ) but this was translated as as string from the preproccesor.

Also, I tried from other macros each time they called to #undef X and redefine X according what to do in my line, etc.


Solution

  • The preprocessor is not sufficiently complex to allow for things like context-dependent replacement! The preprocessor understands nothing about C++ syntax, it literally runs before the C++ parser. But you would need your preprocessor to "understand" where you need a closing symbol, and it can't do that.

    And looking at the way it's standardized, I think that's intentional.

    In short: you can't build a DSL that requires this. In all honestly, modern C++ is flexible enough that you can build a DSL within C++ itself, but you'd of course still be bound by C++'s general syntax. If you need something else, I'd say that C++ & the standard preprocessor probably is not the tool you need.

    That being said, if you're content with putting your DSL into C++ string literals like "…", then you can do a compile-time DSL using constexpr parsing – which is exactly what @vitaut's {fmt} implements a string formatting DSL within C++.