The state of string interpolation

H. S. Teoh hsteoh at quickfur.ath.cx
Thu Dec 6 21:32:22 UTC 2018


On Thu, Dec 06, 2018 at 09:06:16PM +0000, Neia Neutuladh via Digitalmars-d wrote:
> On Thu, 06 Dec 2018 20:45:57 +0000, Meta wrote:
> > On Thursday, 6 December 2018 at 20:00:02 UTC, H. S. Teoh wrote:
> >> Essentially, what you want to be able to do is essentially for a
> >> template to be able to reference symbols in the caller's scope,
> >> rather than in the template's scope.
> > 
> > Am I missing something? D has this already in the form of mixin
> > templates.
> 
> >From the spec:
> 
> "A TemplateMixin can occur in declaration lists of modules, classes,
> structs, unions, and as a statement."
> 
> Also, it still requires the `mixin` keyword at the place of instantiation. 
> 
> So you want to write:
> 
>     writeln(interp!"Hi, ${user.name}!");
> 
> But you currently have to write:
> 
>     mixin interp!"Hi, ${user.name}!";
>     writeln(interpResult);

Ah, so mixin templates *can* access symbols from the containing scope.
That's nice... so actually, we can already implement string
interpolation in the library.  The only complaint is the ugly syntax
required `mixin blah!"abc ${def}"` instead of simply `blah!"abc ${def}"`
or `blah("abc ${def}")`.

I'm in favor of making the syntax less ugly, but I fear Andrei's
objection is going to be that (1) this is already possible without a
language change, and (2) the proposed language change would effectively
only add syntactic sugar, which is unlikely to be enough justification
for doing it.

The above syntax *could* possibly be made just slightly less ugly, if we
extended mixin templates to allow mixin *expressions*, e.g.:

	writeln(mixin interp!"Hi, ${user.name}!");

instead of needing to break it into two lines and accessing an implicit
symbol. Having to break it into two lines is really a serious blow to
writability / usability.  I'd like to get rid of the `mixin` as well,
but I have a feeling Andrei isn't going to like that.

Or perhaps, one could employ the alternative:

	mixin interpFun!(writeln, "Hi, ${user.name}");

where the interpFun template essentially implements the function call on
your behalf.  This is essentially a hack, though, and wouldn't be easily
extendible to the general case without further contortions.  Extending
mixin templates to allow expressions seems to be the least undesirable
option, barring actually adding string interpolation support to the
compiler / language spec.


T

-- 
Don't get stuck in a closet---wear yourself out.


More information about the Digitalmars-d mailing list