DIP idea: q{}-inspired block mixins

Q. Schroll qs.il.paperinik at gmail.com
Wed Jun 10 03:03:49 UTC 2020


Mixin declarations and statements are often used in conjunction 
with large literals containing lots of code, where stuff is 
inserted at specific points using interruptions like mixin("...", 
identifier, "...") or %s format specifiers and .format afterwards.
It hurts readability. In the best case, code should directly 
express what we mean.
We mean in those cases: Insert the value of identifier and not 
"identifier" here.
An observation is also that hardly anywhere, the value of the 
identifier and not "identifier" are used together.

Suggestion:

     mixin[op]
     {
         lhs op= rhs;
     }

It parses the stuff between the { and } the same as a q{}-string, 
but any identifier token found that is identical to the one 
between [ and ] will not be used literally, but be evaluated 
(mixed in). So the above is equivalent to:

     mixin("lhs ", op, "= rhs;");

For a simple idea(*): Pack everything between the braces in a q{} 
string. "Interrupt" the q{} string anywhere an identifier `ident` 
of the bracketed list is found by "},ident,q{".
(*) Doesn't work when braces are involved.

A prime example is pseudo-code we have on the spec that doesn't 
compile. We often write stuff like op= and expect people to 
interpret it properly. With that, the compiler could, too.

FAQ.

Q: Can I use multiple identifiers?
A: Yes. Comma-separated in the brackets. E.g. [ident1, ident2]

Q: Can I use expressions?
A: Instead of a plain identifier, use [ident = expression()].

Q: So [ident] alone is equivalent to [ident = ident]?
A: You got the idea right, but you cannot actually write that. 
Use [ident] or [ident2 = ident].

Q: Can I mix assignments and single identifiers?
A: Sure.

Q: Where can I use it?
A: Anywhere a mixin() statement or declaration can be. It's just 
an alternative syntax to mixin per se. Potentially also 
everywhere a {}-block can be. (Let's see what others think about 
that.)

Q: Wait, what about mixin() expressions?
A: Unfortunately not those. Block mixins are for complete 
statements or delcarations (depending on the context). Note that 
the examples didn't use a semicolon at their end.

Q: Can I use the identifiers in [ and ] in the block mixin 
without being mixed in (i.e. "escaped" in some sense)?
A: No. Use [ident2 = ident]. Then ident will not be replaced by 
its value.

Syntax up for debate.

Disclaimer: I don't really know how q{} strings are lexed and 
parsed. I'd assume the they're lexed as separate tokens, parsed 
token-wise until the closing brace is found.

What do you think about it?


More information about the Digitalmars-d mailing list