Programming in D – Tutorial and Reference
Ali Çehreli

Other D Resources

Mixins

Mixins are for mixing in generated code into the source code. The mixed in code may be generated as a template instance or a string.

Template mixins

We have seen in the Templates and More Templates chapters that templates define code as a pattern, for the compiler to generate actual instances from that pattern. Templates can generate functions, structs, unions, classes, interfaces, and any other legal D code.

Template mixins insert instantiations of templates into the code by the mixin keyword:

    mixin a_template!(template_parameters)

As we will see in the example below, the mixin keyword is used in the definitions of template mixins as well.

The instantiation of the template for the specific set of template parameters is inserted into the source code right where the mixin keyword appears.

For example, let's have a template that defines both an array of edges and a pair of functions that operate on those edges:

mixin template EdgeArrayFeature(T, size_t count) {
    T[count] edges;

    void setEdge(size_t index, T edge) {
        edges[index] = edge;
    }

    void printEdges() {
        writeln("The edges:");

        foreach (i, edge; edges) {
            writef("%s:%s ", i, edge);
        }

        writeln();
    }
}

That template leaves the type and number of array elements flexible. The instantiation of that template for int and 2 would be mixed in by the following syntax:

    mixin EdgeArrayFeature!(int, 2);

For example, the mixin above can insert the two-element int array and the two functions that are generated by the template right inside a struct definition:

struct Line {
     mixin EdgeArrayFeature!(int, 2);
}

As a result, Line ends up defining a member array and two member functions:

import std.stdio;

void main() {
    auto line = Line();
    line.setEdge(0, 100);
    line.setEdge(1, 200);
    line.printEdges();
}

The output:

The edges:
0:100 1:200 

Another instantiation of the same template can be used e.g. inside a function:

struct Point {
    int x;
    int y;
}

void main() {
    mixin EdgeArrayFeature!(Point, 5);

    setEdge(3, Point(3, 3));
    printEdges();
}

That mixin inserts an array and two local functions inside main(). The output:

The edges:
0:Point(0, 0) 1:Point(0, 0) 2:Point(0, 0) 3:Point(3, 3) 4:Point(0, 0) 
Template mixins must use local imports

Mixing in template instantiations as is can cause problems about the modules that the template itself is making use of: Those modules may not be available at the mixin site.

Let's consider the following module named a. Naturally, it would have to import the std.string module that it is making use of:

module a;

import std.string;    // ← wrong place

mixin template A(T) {
    string a() {
        T[] array;
        // ...
        return format("%(%s, %)", array);
    }
}

However, if std.string is not imported at the actual mixin site, then the compiler would not be able to find the definition of format() at that point. Let's consider the following program that imports a and tries to mix in A!int from that module:

import a;

void main() {
    mixin A!int;    // ← compilation ERROR
}
Error: undefined identifier format
Error: mixin deneme.main.A!int error instantiating

For that reason, the modules that template mixins use must be imported in local scopes:

module a;

mixin template A(T) {
    string a() {
        import std.string;    // ← right place

        T[] array;
        // ...
        return format("%(%s, %)", array);
    }
}

As long as it is inside the template definition, the import directive above can be outside of the a() function as well.

Identifying the type that is mixing in

Sometimes a mixin may need to identify the actual type that is mixing it in. That information is available through this template parameters as we have seen in the More Templates chapter:

mixin template MyMixin(T) {
    void foo(this MixingType)() {
        import std.stdio;
        writefln("The actual type that is mixing in: %s",
                 MixingType.stringof);
    }
}

struct MyStruct {
    mixin MyMixin!(int);
}

void main() {
    auto a = MyStruct();
    a.foo();
}

The output of the program shows that the actual type is available inside the template as MyStruct:

The actual type that is mixing in: MyStruct
String mixins

Another powerful feature of D is being able to insert code as string as long as that string is known at compile time. The syntax of string mixins requires the use of parentheses:

    mixin (compile_time_generated_string)

For example, the hello world program can be written with a mixin as well:

import std.stdio;

void main() {
    mixin (`writeln("hello world");`);
}

The string gets inserted as code and the program produces the following output:

hello world

We can go further and insert all of the program as a string mixin:

mixin (
`import std.stdio; void main() { writeln("hello world"); }`
);

Obviously, there is no need for mixins in these examples, as the strings could have been written as code as well.

The power of string mixins comes from the fact that the code can be generated at compile time. The following example takes advantage of CTFE to generate statements at compile time:

import std.stdio;

string printStatement(string message) {
    return `writeln("` ~ message ~ `");`;
}

void main() {
    mixin (printStatement("hello world"));
    mixin (printStatement("hi world"));
}

The output:

hello world
hi world

Note that the "writeln" expressions are not executed inside printStatement(). Rather, printStatement() generates code that includes writeln() expressions that are executed inside main(). The generated code is the equivalent of the following:

import std.stdio;

void main() {
    writeln("hello world");
    writeln("hi world");
}
Mixin name spaces

It is possible to avoid and resolve name ambiguities in template mixins.

For example, there are two i variables defined inside main() in the following program: one is defined explicitly in main and the other is mixed in. When a mixed-in name is the same as a name that is in the surrounding scope, then the name that is in the surrounding scope gets used:

import std.stdio;

template Templ() {
    int i;

    void print() {
        writeln(i);  // Always the 'i' that is defined in Templ
    }
}

void main() {
    int i;
    mixin Templ;

    i = 42;      // Sets the 'i' that is defined explicitly in main
    writeln(i);  // Prints the 'i' that is defined explicitly in main
    print();     // Prints the 'i' that is mixed in
}

As implied in the comments above, template mixins define a name space for their contents and the names that appear in the template code are first looked up in that name space. We can see this in the behavior of print():

42
0     ← printed by print()

The compiler cannot resolve name conflicts if the same name is defined by more than one template mixin. Let's see this in a short program that mixes in the same template instance twice:

template Templ() {
    int i;
}

void main() {
    mixin Templ;
    mixin Templ;

    i = 42;        // ← compilation ERROR
}
Error: deneme.main.Templ!().i at ... conflicts with
deneme.main.Templ!().i at ...

To prevent this, it is possible to assign name space identifiers for template mixins and refer to contained names by those identifiers:

    mixin Templ A;    // Defines A.i
    mixin Templ B;    // Defines B.i

    A.i = 42;         // ← not ambiguous anymore

String mixins do not have these name space features. However, it is trivial to use a string as a template mixin simply by passing it through a simple wrapper template.

Let's first see a similar name conflict with string mixins:

void main() {
    mixin ("int i;");
    mixin ("int i;");    // ← compilation ERROR

    i = 42;
}
Error: declaration deneme.main.i is already defined

One way of resolving this issue is to pass the string through the following trivial template that effectively converts a string mixin to a template mixin:

template Templatize(string str) {
    mixin (str);
}

void main() {
    mixin Templatize!("int i;") A;    // Defines A.i
    mixin Templatize!("int i;") B;    // Defines B.i

    A.i = 42;                         // ← not ambiguous anymore
}
String mixins in operator overloading

We have seen in the Operator Overloading chapter how mixin expressions helped with the definitions of some of the operators.

In fact, the reason why most operator member functions are defined as templates is to make the operators available as string values so that they can be used for code generation. We have seen examples of this both in that chapter and its exercise solutions.

Mixed in destructors

It is possible to mix in multiple destructors to a user defined type. Those destructors are called in the reverse order of the mixin statements that added them. This feature allows mixing in different resources to a type, each introducing its own of cleanup code.

import std.stdio;

mixin template Foo() {
    ~this() {
        writeln("Destructor mixed-in by Foo");
    }
}

mixin template Bar() {
    ~this() {
        writeln("Destructor mixed-in by Bar");
    }
}

struct S {
    ~this() {
        writeln("Actual destructor");
    }
    mixin Foo;
    mixin Bar;
}

void main() {
    auto s = S();
}
Destructor mixed-in by Bar
Destructor mixed-in by Foo
Actual destructor

Due to a bug as of this writing, the same behavior does not apply to other special functions like constructors. Additionally, a destructor mixed in by a string mixin does conflict with the existing destructor of the type.

Example

(Note: Specifying predicates as strings was used more commonly before the lambda syntax was added to D. Although string predicates as in this example are still used in Phobos, the => lambda syntax may be more suitable in most cases.)

Let's consider the following function template that takes an array of numbers and returns another array that consists of the elements that satisfy a specific condition:

int[] filter(string predicate)(in int[] numbers) {
    int[] result;

    foreach (number; numbers) {
        if (mixin (predicate)) {
            result ~= number;
        }
    }

    return result;
}

That function template takes the filtering condition as its template parameter and inserts that condition directly into an if statement as is.

For that condition to choose numbers that are e.g. less than 7, the if condition should look like the following code:

        if (number < 7) {

The users of filter() template can provide the condition as a string:

    int[] numbers = [ 1, 8, 6, -2, 10 ];
    int[] chosen = filter!"number < 7"(numbers);

Importantly, the name used in the template parameter must match the name of the variable used in the implementation of filter(). So, the template must document what that name should be and the users must use that name.

Phobos uses names consisting of single letters like a, b, n, etc.