Mixed up over mixins.

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Aug 21 07:21:04 PDT 2017


On 8/21/17 3:29 AM, WhatMeForget wrote:
> On Sunday, 20 August 2017 at 19:41:14 UTC, Ali Çehreli wrote:
>> On 08/20/2017 12:27 PM, WhatMeWorry wrote:
>>
>> >     // 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.
>>
>> Yes, it means that the string must be legal D code.
>>
>> >     mixin(`writeln(` ~ `Hello`  ~ `);` );
>>
>> Yes, that's a D string but the string itself is not legal D code 
>> because it would be mixing in the following:
>>
>>     writeln(Hello);
>>
>> The problem is, there is no Hello defined in the program.
>>
>> You need to make sure that Hello is a string itself:
>>
>>     writeln("Hello");
>>
>> So, you need to use the following mixin:
>>
>>     mixin(`writeln(` ~ `"Hello"`  ~ `);` );
>>
> 
> Of course, why didn't I "see" that before. I should have slept on it and 
> tried again with fresh eyes.  I'm keeping a "beginners journal" on code 
> generation.  Maybe write a 101 introduction with lots of samples and 
> exercises.

When doing mixins, especially when the code to generate the mixin string 
isn't a simple literal, a great thing to do is to use pragma(msg) to 
show the actual string you are mixing in.

e.g.:
enum mixinstr = ...
pragma(msg, mixinstr);
mixin(mixinstr);

Often times, your error is obvious when you see it that way.

-Steve


More information about the Digitalmars-d-learn mailing list