string interpolation fun

Jonathan Marler johnnymarler at
Thu Dec 13 16:36:01 UTC 2018

On Thursday, 13 December 2018 at 16:21:48 UTC, Jonathan Marler 
> On Thursday, 13 December 2018 at 16:01:52 UTC, Steven 
> Schveighoffer wrote:
>> On 12/13/18 10:53 AM, Steven Schveighoffer wrote:
>>> void main()
>>> {
>>>      import std.stdio;
>>>      int x = 1;
>>>      int y = 2;
>>>      auto s = make!(S, i"x: $(y), y: $(x)"); // name the 
>>> fields to assign
>>>      auto s2 = make!(S, i":$(x), :$(y)"); // use symbol name 
>>> as field name
>>>      auto s3 = make!(S, i"x: $(6), y: $(7)"); // use literals 
>>> to assign
>>>      writeln(i"$(s), $(s2), $(s3)"); // runtime parameters
>>> }
>> Also, this would be a lot less noisy if we didn't need the 
>> parens after the $, but the PR doesn't support that (yet?).
>> -Steve
> Very cool use case.
> Adding support for the `$foo` case (no parens) would be fairly 
> trival, but requires making a decision of what type of grammar 
> node/token to use.  We could use the same mechanism that 
> templates use, but that would mean that something like $foo.max 
> would be $(foo).max instead of $(foo.max) which seems a bit 
> unexpected.  That would be a good thing include in the DIP, a 
> list of the obvious tokens/grammar nodes we could use and their 
> pros/cons.

I should add, the strategy I used in the PR was to establish the 
"foundation" of interpolated strings and postpone any unnecessary 
decisions so they didn't prevent the foundation from being 
merged.  The idea was to be able to merge the change so that it 
could be experimented with without disturbing the rest of the 
compiler.  After it was merged and we could get some experience 
with it and we could later decide what features to add later.

I was pleasantly surprised at how little the new feature affected 
the compiler. I didn't even need a grammar change. I just 
modified the lexer to detect the letter 'i' before string 
literals and then in the parse stage lowered those string 
literals to tuples.  It only affected the existing compiler in 2 
places, very low impact and encapsulated.

More information about the Digitalmars-d mailing list