DIP 1027---String Interpolation---Community Review Round 1
Adam D. Ruppe
destructionator at gmail.com
Fri Dec 13 00:06:15 UTC 2019
On Thursday, 12 December 2019 at 17:03:53 UTC, Atila Neves wrote:
> It'd be great if you could expand on this with a list of
> examples of what D could do.
Of course, there's the examples of printf, writeln, sql query..
(One other addition I might make to my proposal is having the
string version of what's in the thing too, but I digress). Those
are the easy ones.
Note btw that you can even do a format!"%s"(a) type thing.
format!i"#{a}" can be transformed.
But it can get pretty interesting to look beyond function calls.
What about some kind of object literal?
int a;
string b;
JSONValue j = json!iq{
a: #{a},
b: #{b}
};
That specific syntax assumes interpolated token strings are a
thing but it could just as well be
JSONValue j = json!i"
a: #{a},
b: #{b}
";
or %(a) or $a or whatever. I don't care.
The implementation would look something like:
JSONValue json(__d_interpolated_string s)() {
JSONValue j;
foreach(idx, member; s.tupleof) {
static if(!(idx & 1)) {
j.object[member.replace(",", "").strip] =
JSONValue(member[idx + 1]());
}
}
return j;
}
you know plus more sanity but you get the idea. All the data is
in an object which we can pass to a template to do compile time
checking and return type processing etc.
Of course, for json, you can do a built in AA and a constructor
from it, just then the types have to be heterogeneous. Not a huge
deal for json but it can get ugly nested. But we can do xml too,
think react's jsx
int foo;
string bar = "<";
Element e = jsx!i`
<foo value=#{foo}>#{bar}</foo>
`;
assert(e.tagName = "foo");
assert(e.attrs.value == foo);
assert(e.innerHTML == "<");
This is almost interchangeable with the mixin(foo!"string")
thing... in fact you could implement it that way, just instead of
having foo!xx return a code string the compiler helps a bit more.
More information about the Digitalmars-d
mailing list