Create mixins from a list of strings

Philippe Sigaud philippe.sigaud at gmail.com
Sat Jan 11 08:52:22 PST 2014


> Note that closures are not (yet) supported in CTFE, because else
> another solution would be a function-returning function:
>
> auto bar(string s, int i)
> {
>     return
>         (ParseTree p) {
>             p.name ~= s ~ to!string(i);
>             return p;
>         };
> }

Duh, instead of closures, you can use opCall-ed structs:

import pegged.grammar;

auto foo(string s, int i)
{
     return Foo(s,i);
}

struct Foo
{
    string s;
    int i;
    this(string s, int i) { this.s = s; this.i = i;}
    ParseTree opCall(ParseTree p)
    {
        p.name ~= s ~ to!string(i);
        return p;
    }
}


mixin(grammar(`
Test:
    A <- B { foo("abc",1) } C { foo("def",2) }
    B <- 'b'
    C <- 'c'
`));

void main()
{
    enum result = Test("bc"); // Compile-time parsing is still possible
    pragma(msg, result);
    writeln(result);
}


More information about the Digitalmars-d-learn mailing list