| 1 |
import core.interpolation; |
| 2 |
|
| 3 |
alias AliasSeq(T...) = T; |
| 4 |
|
| 5 |
string simpleToString(T...)(T thing) { |
| 6 |
string s; |
| 7 |
foreach(item; thing) |
| 8 |
// all the items provided by core.interpolation have |
| 9 |
// toString to return an appropriate value |
| 10 |
// |
| 11 |
// then this particular example only has embedded strings |
| 12 |
// and chars, to we can append them directly |
| 13 |
static if(__traits(hasMember, item, "toString")) |
| 14 |
s ~= item.toString(); |
| 15 |
else |
| 16 |
s ~= item; |
| 17 |
|
| 18 |
return s; |
| 19 |
} |
| 20 |
|
| 21 |
void main() { |
| 22 |
int a = 1; |
| 23 |
string b = "one"; |
| 24 |
// parser won't permit alias = i".." directly; i"..." is meant to |
| 25 |
// be used as a function/template parameter at this time. |
| 26 |
alias expr = AliasSeq!i"$(a) $(b)"; |
| 27 |
// elements from the source code are available at compile time, so |
| 28 |
// we static assert those, but the values, of course, are different |
| 29 |
static assert(expr[0] == InterpolationHeader()); |
| 30 |
static assert(expr[1] == InterpolatedExpression!"a"()); |
| 31 |
assert(expr[2] == a); // actual value not available at compile time |
| 32 |
static assert(expr[3] == InterpolatedLiteral!" "()); |
| 33 |
// the parens around the expression are not included |
| 34 |
static assert(expr[4] == InterpolatedExpression!"b"()); |
| 35 |
assert(expr[5] == b); // actual value not available at compile time |
| 36 |
static assert(expr[6] == InterpolationFooter()); |
| 37 |
|
| 38 |
// it does currently allow `auto` to be used, it creates a value tuple |
| 39 |
// you can embed any D expressions inside the parenthesis, and the |
| 40 |
// token is not ended until you get the *outer* ) and ". |
| 41 |
auto thing = i"$(b) $("$" ~ ')' ~ `"`)"; |
| 42 |
assert(simpleToString(thing) == "one $)\""); |
| 43 |
|
| 44 |
assert(simpleToString(i"$b") == "$b"); // support for $ident removed by popular demand |
| 45 |
|
| 46 |
// i`` and iq{} should also work |
| 47 |
assert(simpleToString(i` $(b) is $(b)!`) == " one is one!"); |
| 48 |
assert(simpleToString(iq{ $(b) is $(b)!}) == " one is one!"); |
| 49 |
assert(simpleToString(i`\$('$')`) == "\\$"); // no \ escape there |
| 50 |
assert(simpleToString(iq{{$('$')}}) == "{$}"); // {} needs to work |
| 51 |
} |