On Wednesday, 15 March 2017 at 13:50:28 UTC, Inquie wrote:
I hate building code strings for string mixins as it's very
ugly and seems like a complete hack.
How bout, instead, we have a special code string similar to a
multiline string that allows us to represent valid D code. The
compiler can then verify the string after compilation to make
sure it is valid D code(since it ultimately is a compile time
constant).
e.g.,
string s = "smile";
enum code1 = @#
void happyCode = "Makes me @@s@@";
#@
enum code2 = code1 ~ @#
int ImThisHappy = @@s.length@@;
#@
mixin(code);
or
mixin(code.stringof); // possible to convert code string to a
string and vice versa.
or whatever syntax one thinks is better. The point is that the
code string is specified different and then is no longer
ambiguous as a normal string. Compilers and IDE's can make more
informed decisions.
There might be a much better way, but something should be done
to clean up this area of D. It is a mess to have to use string
building to create code. (it's amazingly powerful, but still a
mess)
I've got a PR for dmd (https://github.com/dlang/dmd/pull/7988)
that implements "interpolated strings" which makes generating
code with strings MUCH nicer, i.e.
string generateFunction(string attributes, string returnType,
string name, string args, string body)
{
import std.conv : text;
return text(iq{
// This is an interpolated string!
$(attributes) $(returnType) $(name)($(args))
{
$(body)
}
});
}
// Let's use it:
mixin(generateFunction("pragma(inline)", "int", "add", "int a,
int b", "return a + b;"));
assert(100 == add(25, 75));