Thread overview
Going from string to identifier
Feb 21, 2018
Jean-Louis Leroy
Feb 21, 2018
Meta
Feb 21, 2018
Adam D. Ruppe
Feb 21, 2018
Basile B.
February 21, 2018
Here's what I am trying to do:

mixin template MakeFun(string ID, int X)
{
  int mixin(ID)() { return X; }
}

mixin MakeFun!("one", 1); // int one() { return 1; }

Alas I get:
makefunc.d(3): Error: no identifier for declarator `int`
makefunc.d(3): Error: found `{` when expecting `;`
makefunc.d(3): Error: declaration expected, not `return`
makefunc.d(4): Error: unrecognized declaration

Is there a shorter way than building the entire function definition as a string mixin? As in:

mixin template MakeFun(string ID, int X)
{
  import std.format;
  mixin(format("int %s() { return %s; }", ID, X));
}

mixin MakeFun!("one", 1);

February 21, 2018
On Wednesday, 21 February 2018 at 22:11:04 UTC, Jean-Louis Leroy wrote:
> Here's what I am trying to do:
>
> mixin template MakeFun(string ID, int X)
> {
>   int mixin(ID)() { return X; }
> }
>
> mixin MakeFun!("one", 1); // int one() { return 1; }
>
> Alas I get:
> makefunc.d(3): Error: no identifier for declarator `int`
> makefunc.d(3): Error: found `{` when expecting `;`
> makefunc.d(3): Error: declaration expected, not `return`
> makefunc.d(4): Error: unrecognized declaration
>
> Is there a shorter way than building the entire function definition as a string mixin? As in:
>
> mixin template MakeFun(string ID, int X)
> {
>   import std.format;
>   mixin(format("int %s() { return %s; }", ID, X));
> }
>
> mixin MakeFun!("one", 1);

Mixins have to be full declarations. You can't mix in bits and pieces... except when you can:

import std.stdio;

void main()
{
    enum teste = "asdf";
    string s = mixin("teste");
    writeln(s); //Prints "asdf"
}

It looks like a grammar error as opposed to a semantic one. D's grammar just doesn't support `mixin` in the function name position. One way you can make it a little more palateable:

mixin template MakeFun(string ID, int X)
{
    import std.format;
    mixin(q{ int %s { return %s; } }.format(ID, X));
}

`q{}` denotes a token string that must contain valid tokens (I'm not sure if the available compiler implementations actually enforce this), and I _think_ token strings will be properly syntax-highlighted by most tools.

https://dlang.org/spec/lex.html#token_strings
February 21, 2018
On Wednesday, 21 February 2018 at 22:22:55 UTC, Meta wrote:
> Mixins have to be full declarations.

They need to be full declarations, full statements, or full expressions, depending on the context where they appear.

>     string s = mixin("teste");

so that is a full expression and thus legal.
February 21, 2018
On Wednesday, 21 February 2018 at 22:22:55 UTC, Meta wrote:
> (I'm not sure if the available compiler implementations actually enforce this)

Yes it does, example

```
enum s = q{€};
```

gives: `Error: character 0x20ac is not a valid token`