Self-referential struct mixins

Claude claudemr at
Sun Nov 17 09:16:19 UTC 2019

On Sunday, 17 November 2019 at 07:13:52 UTC, rbscott wrote:
> Hello,
> I recently started using D, and I am exploring some of the 
> functionality in CTFE. I ran into a case that I can't get past. 
> The goal is to take a JSON API Schema and convert it into D 
> types using CTFE. The problem is, the types can be 
> self-referential.
> A simplified form of the language would look like:
> { "A" : { "type": struct, "fields" : { "b": { "type": "string" 
> }, "a" : { "type": "A" }}}
> This would yield a type "A" that has two fields, "a" and "b". 
> Where "a" is a string and "b" is of type "A". Or in D:
> struct A {
>   string b;
>   A* a;
> }
> This is a simplified example, but imagine this is highly nested 
> to generate arbitrarily complex types that could reference on 
> one another.
> I got this working in the simple case if none of the fields are 
> self-referential, but it breaks as soon as there is a loop.
> Here is a gist which demonstrates the issue: 
> I think I can workaround this by with string mixins everywhere, 
> but the structure generation logic is complex enough that I 
> would prefer not to do that. This approach could be totally 
> off, so any suggestions would be greatly appreciated!
> thanks,
> rbscott

But "a" is not strictly of type A, but rather A*, which makes a 
big difference.

Anyway, upon the mixin template instantiation, you can try to 
'declare' all your struct's on top and then properly 'define' 
them afterwards:

struct A;
struct B;

struct A {
   B* b;

struct B {
   A* a;

Have you tried that?

More information about the Digitalmars-d mailing list