Generating unique identifiers at compile time

Paul Backus snarwin at gmail.com
Sun Jun 12 18:45:27 UTC 2022


On Thursday, 9 June 2022 at 21:20:27 UTC, JG wrote:
> In doing so I wanted to produce unique identifiers (something 
> like gensym in racket.) I did this in a very hacky way:
[...]
> Is there some way to ask the compiler for a unique name or a 
> better way of achieving this?

Here's a `gensym` implementation I came up with a while back:

```d
enum gensym = q{"_gensym" ~ __traits(identifier, 
{})["__lambda".length .. $]};

// Works multiple times on the same line
pragma(msg, mixin(gensym)); pragma(msg, mixin(gensym));
```

This takes advantage of the fact that the compiler generates a 
unique identifier for every lambda function it encounters. While 
you can't actually use those identifiers in your code, they are 
visible in error messages and can be accessed via 
`__traits(identifier)`.


More information about the Digitalmars-d-learn mailing list