Dollar identifiers in code-generating constructs
Meta
jared771 at gmail.com
Mon Jul 15 17:50:10 UTC 2024
On Wednesday, 3 July 2024 at 10:25:14 UTC, Quirin Schroll wrote:
> A dollar identifier is an
> [*`Identifier`*](https://dlang.org/spec/lex.html#Identifier)
> with a `$` at the end. In a code-generating construct (mixed-in
> `mixin template` and `static foreach`/`static foreach_reverse`)
> the `$` is replaced by a number.
>
> For a loop, it is the index of iteration.
>
> For a mixin template, it is the number of mixin templates mixed
> in up until this point.
>
> ---
>
> ### Example: loop
>
> ```d
> enum xs = ["A", "BC", "DEF"];
> static foreach (x; xs)
> {
> size_t l = x.length; // Error on "BC" and "DEF", already
> defined.
> }
> ```
>
> ```d
> enum xs = ["A", "BC", "DEF"];
> static foreach (x; xs)
> {
> size_t l$ = x.length; // Good: becomes `l0`, `l1`, `l2`
> }
> ```
>
> ### Example: mixin template
>
> ```d
> mixin template mixMeIn(T)
> {
> alias R = int delegate(T);
> }
>
> struct S
> {
> mixin mixMeIn!int; // Okay
> mixin mixMeIn!int; // Error, `R` already defined
> }
> ```
>
> ```d
> mixin template mixMeIn(T)
> {
> alias R$ = int delegate(T);
> }
>
> struct S
> {
> mixin mixMeIn!int; // Okay, defines `R0`
> mixin mixMeIn!int; // Okay, defines `R1`
> }
> ```
This is very similar to a proposal by Timon Gehr to add `__local`
variables that are local to static foreach bodies:
https://github.com/dlang/DIPs/blob/master/DIPs/accepted/DIP1010.md#local-declarations
More information about the dip.ideas
mailing list