DEV Community

Jesse Phillips
Jesse Phillips

Posted on

String Mixin

mixin

D provides two features under the name mixin template mixin and string mixin. I will only be covering string mixin at this time.

The idea here is to take a string which defines valid D source code and inject it for compilation. Let's start with something simple.

mixin("int a;");
mixin("a = 6;");
assert(a == 6);
Enter fullscreen mode Exit fullscreen mode

This is not very effective practice for standard coding. This is not the same as macros like those in C, D requires the string to contain a complete statement(s).

if(mixin("a == ") 6) // failure 
Enter fullscreen mode Exit fullscreen mode

D won't just inject the string into the code. It requires a complete declarations, statements, or expressions.

It is possible to use these generated code blocks with CTFE.

int addTwo(int a) {
    mixin("a += 2;");
    return a;
} 

static assert(addTwo(4) == 6);
Enter fullscreen mode Exit fullscreen mode

Operator Overloading

Docs

void main()
{
    auto a = new T;
    auto b = new T;
    a.data = 1;
    b.data = 2;
    assert((a + b).data == 3);
    assert((b - a).data == 1);
}

class T { 
    int data;
    T opBinary(string op)(T rhs)
    {
        T ret = new T();
        ret.data = mixin("data "~op~" rhs.data");

        return ret;
    }
} 
Enter fullscreen mode Exit fullscreen mode

D has chosen to use templates and allow mixin to handle operator overloading.

Code Builder

I started working on improving a protocol buffer generator for D (fixing bugs and generating better API for D. In doing so I found the code snippets which generates the structure lacking. So I built Codebuilder.

Why is it relevant to mixin? Because it works at compile-time (and runtime). This means the code builder results could be mixed in and compiled. I almost completed making the protobuf library use .proto files as "D code" (I think I left off on cross referencing. Also many of the unittests ran at compilation.)

GitHub logo JesseKPhillips / codebuilder

Used to manage code generation.

Build Code

This library provides a structured way to build source code from strings. It is intended for use with the D programming language, but can be utilized for other languages as well. The key piece specific to D is the automatically injected line/file insertions.

When D mixes in a string for further compilation, errors compiling that string will start pointing to source code which does not exist. By utilizing this library to build out the code structure, the compiler will point to the source line which inserted the piece of code. This will hide where the mixin took place, but direct your attention to the offending source structure.

Why use a Code Builder

When generating source code, variables and strings are concatenated together to build out new code. This can become very ugly, be it using a string formatter or plain old concatenation. Code Builder tries to allow for…

Top comments (0)