Thread overview
mixin issue
Nov 29
DLearner
Nov 29
Dennis
November 29

The code:

void main() {

   struct SB {
      char  SBChrFld1;
      char  SBChrFld2;
      int   SBIntFld1;
      int   SBIntFld2;
   }
   SB  SBVar;

   SB* wkSBPtr;


   void* StartPtr1 = null;

   mixin(mxnDelMbr("StartPtr1", "wkSBPtr"));
   return;
}

string mxnDelMbr()(string strStartPtr, string strPLPtr) {
   return `(void* StartPtr, typeof(` ~ strPLPtr ~ `) PLPtr) {

   }(` ~ strStartPtr ~ `,` ~ strPLPtr ~ `)`;
}

Fails with:

Error: found `End of File` when expecting `;` following statement

If an extra ; is added:

   }(` ~ strStartPtr ~ `,` ~ strPLPtr ~ `);`;

it works but doesn't seem correct.
Further, example above cloned from several other similar examples, which
not only work, but if ';' introduced in corresponding place, dmd complains with
empty statement deprecation.
FWIW only difference identified between successful examples and this one,
is that other functions all return something, this one does not.

Suggestions?

November 29

On Wednesday, 29 November 2023 at 13:31:14 UTC, DLearner wrote:

>

it works but doesn't seem correct.

You're mixing in an expression that creates an empty function and calls it. What do you want it to do?

November 29

On Wednesday, 29 November 2023 at 13:31:14 UTC, DLearner wrote:

>
Error: found `End of File` when expecting `;` following statement

If an extra ; is added:

   }(` ~ strStartPtr ~ `,` ~ strPLPtr ~ `);`;

it works but doesn't seem correct.

This is an annoying limitation of the D compiler.

The root of the problem is that there is an ambiguity in D's grammar. When the compiler sees

mixin(whatever);

...it cannot tell whether it's supposed to be a Mixin Statement, or an Expression Statement that contains a Mixin Expression.

If it's a Mixin Statement, then there should be a semicolon inside the mixin. If it's an Expression Statement with a Mixin Expression, then there shouldn't be a semicolon inside the mixin.

To resolve this ambiguity, the compiler (currently) assumes that it's always a Mixin Statement, which means that it will always require a semicolon inside the mixin.

As a result, it is impossible to write a string mixin that can be used as both a statement and an expression.

If you have an expression mixin and you would like to use it as a statement, you can work around this limitation by adding cast(void) in front of the mixin:

cast(void) mixin(whatever);

This forces the compiler to parse the line as an Expression Statement containing a Cast Expression, but does not otherwise change the meaning of the code.