mixin does not work as expected

H. S. Teoh hsteoh at quickfur.ath.cx
Thu Jan 6 00:26:19 UTC 2022


On Wed, Jan 05, 2022 at 11:29:08PM +0000, Era Scarecrow via Digitalmars-d-learn wrote:
[...]
>  That said, rolling your own mixins should really be the last resort.
>  You're dumping a lot into a single line of code you can't trace,
>  follow, debug, or look at.

Mixins are kinda like the nuclear option when nothing else would work.
Generally, they should be avoided if there are less drastic ways of
achieving what you want.  Don't kill an ant with a nuclear warhead.

Having said that, though, the usual way I use string mixins is to
separately construct the string (usually in a CTFE function that returns
the code string), then hand that to mixin() separately.  The reason: if
something goes wrong, then I can easily write `pragma(msg,
myCtfeCodeGenFunc());` to see exactly what the compiler is choking on,
rather than having to debug code by mentally piecing together a
complicated inline mixin expression.

Also, once my mixin expressions reaches a certain threshold of
complexity, I prefer rather the build-time option of writing a helper
program that generates the code into a .d file, that then gets imported
by the subsequent main compilation step.  That way I can actually see
(and edit!) the generated code to figure out the problem without having
to deal with CTFE-generated mixin expressions. (Certain forms of codegen
are also faster to generate as a separate build step than trying to
shoehorn it into CTFE -- generating code from large data files that
require non-trivial data processing, for example.)

(Off-topic rant: dub doesn't really support this usage very well, which
is one of the reasons I haven't embraced it yet. It's technically
*possible* to do this, but requires jumping through a lot of hoops. It
really should be a LOT more integrated, considering that many D coders
are here because they're into meta-programming, and codegen via a
preliminary step is one of the staples of metaprogramming.)


T

-- 
In order to understand recursion you must first understand recursion.


More information about the Digitalmars-d-learn mailing list