The state of string interpolation

Simen Kjærås simen.kjaras at gmail.com
Fri Dec 7 10:01:36 UTC 2018


On Friday, 7 December 2018 at 05:38:13 UTC, Jonathan Marler wrote:
> All that being said, if someone does find a feature that allows 
> interpolation as a library without mixin and without breaking 
> function isolation then great.  But no feature has been found 
> yet and my confidence that no such feature can exist is growing 
> over time. At some point we'll have to admit the unicorn 
> doesn't exist so let's stick a horn on our horse and paint 
> it...it's not as pretty as the unicorn, but at least its real :)

I've long wished for something like the __CALLER_CONTEXT__ that's 
been suggested elsewhere in this thread, but as has been pointed 
out, it's a maintenance nightmare.

An idea struck me, though: what if __CALLER_CONTEXT__ needed to 
be explicitly passed, and i"" is simply syntactic sugar?

Specifically, i"value: {a+b}" is lowered to 
interpolateString!("value: {a+b}", __traits(getContext)). 
interpolateString is a template in druntime that does the heavy 
lifting.

This would require two new features:

1) __traits(getContext), which returns a scope that can be passed 
to templates, and has some way of invoking mixins in the context 
of that scope (for stuff like i"value: ${a+b}", where simple 
member lookup isn't enough), possibly as context.mixin("a+b").

2) A lowering from i"{a+b}" to interpolateString!("{a+b}", 
__traits(getContext)).

This way we get a shiny new feature to play with and see if there 
are other valuable uses (__traits(getContext)), and a neat way to 
implement string interpolation without destroying every 
expectation of encapsulation. Strictly speaking, 
interpolateString could still do stupid things, but I'd argue we 
should be able to trust code in druntime.

--
   Simen


More information about the Digitalmars-d mailing list