Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 36 ยท Mixins and Metaprogramming

String Mixins in D

Learn D string mixins: how mixin(string) compiles generated source, builds code with CTFE, generates members and operators, and when to avoid them; with C X-macro stand-ins.

A string mixin takes a string known at compile time and compiles it as D code right where the mixin appears. It is the most direct form of metaprogramming in D: write a program (a function that builds a string), run it during compilation, and let its output become part of your program. It is more disciplined than C macros, because the string must contain complete, valid declarations or statements and is parsed by the real compiler.

D code is read-only on this site. The C stand-ins use the preprocessor ("X macros") to generate repeated code from one list, which is the C version of the same idea.

The basic form

D
void main()
{
    mixin("int answer = 6 * 7;");
    writeln(answer);        // 42
}

The compiler parses "int answer = 6 * 7;" and compiles it in the current scope, so answer exists afterwards. The argument must be a compile-time constant string; you cannot mix in text that only exists at run time.

You can also mix in an expression:

D
enum op = "+";
int r = mixin("3 " ~ op ~ " 4");   // 7

Generating code with functions

The real power comes from building strings with ordinary functions evaluated at compile time (see compile-time function execution):

D
string makeGetter(string type, string name)
{
    return type ~ " get_" ~ name ~ "() const { return " ~ name ~ "; }";
}

struct Person
{
    string name;
    int age;
    mixin(makeGetter("string", "name"));
    mixin(makeGetter("int", "age"));
}

Person now has get_name() and get_age() without you typing them. Combine this with a loop over a list of fields and you can generate dozens of members. Since makeGetter is a normal function, you can test it and print its result with pragma(msg, makeGetter("int", "x")) while compiling to see what is being generated.

Generating from a list

The following mixin generates an enum and a function that turns each value into text:

D
string enumWithNames(string name, string[] members)
{
    string code = "enum " ~ name ~ " { ";
    foreach (m; members) code ~= m ~ ", ";
    code ~= "}\n";
    code ~= "string " ~ name ~ "Name(" ~ name ~ " v) {\n  switch (v) {\n";
    foreach (m; members)
        code ~= "    case " ~ name ~ "." ~ m ~ ": return \"" ~ m ~ "\";\n";
    code ~= "    default: return \"?\";\n  }\n}\n";
    return code;
}

mixin(enumWithNames("Color", ["Red", "Green", "Blue"]));

C programmers do the same with an X macro: list the items once, expand the list several times.

C Stand-in: one list generates an enum and a name function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Add one word to COLORS and the enum, the switch and the loop all grow. A D string mixin gives the same single source of truth, but with real code instead of token pasting.

Generating operators

D's operator overloading uses string-based templates, which pair well with mixins. A vector type can generate all four arithmetic operators from one pattern:

D
struct Vec2
{
    double x, y;

    Vec2 opBinary(string op)(Vec2 rhs) const
        if (op == "+" || op == "-")
    {
        return mixin("Vec2(x " ~ op ~ " rhs.x, y " ~ op ~ " rhs.y)");
    }
}

a + b calls opBinary!"+", and the mixin builds the expression Vec2(x + rhs.x, y + rhs.y) from the operator string. One body replaces many near-identical functions.

The stand-in generates the same family from one macro:

C Stand-in: generating +, -, * from one pattern

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Import expressions

D can also read a file at compile time with import("name.txt") (the directory must be allowed with -J on the compiler command line). Combined with mixin, that embeds code or data from a file. Use it for resource files, version strings, or tiny domain languages.

Good habits and pitfalls

  • Prefer templates and static if when they are enough. A string mixin is a last resort for things the type system cannot express, because tools and humans cannot see inside the string.
  • Keep generators small and testable. Return code from a function that has its own unittest.
  • Mix in whole declarations, not fragments of statements that depend on context.
  • Hygiene is manual. The mixed-in code sees the names in the scope where it is placed. A name collision is possible, so use distinctive local names.
  • Print generated text with pragma(msg, ...) when debugging.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What must the argument of mixin(...) be?

    The compiler needs the text during compilation, and it must parse as declarations, statements or an expression.
  2. 2. How do you see the code a generator function produces while compiling?

    pragma(msg, expr) prints a compile-time value during compilation.
  3. 3. In opBinary(string op), what does mixin("x " ~ op ~ " rhs.x") do?

    The concatenated string is compiled as an expression using the actual operator.
  4. 4. When should you prefer something other than a string mixin?

    Mixins are harder to read and debug; use the type-aware features first.

Summary

  • mixin("code") compiles a compile-time string in place.
  • Generator functions plus mixins create members, enums and operators from a list.
  • pragma(msg, ...) and unittest keep generators debuggable.
  • Use mixins sparingly; templates and static if come first.

Next: Mixin Templates