I am working on code generation which takes in an input schema model (Entity Data Model to be precise), and derives Rust types from it.
Types in the schema may be self referential, which means that the generated code may require some indirection - probably Box
ing. For example, my generated code might naively produce the following, causing an "infinite stack size" compile error:
struct Foo {
bar: Option<Bar>,
}
struct Bar {
baz: Baz,
}
struct Baz {
foo: Foo,
}
The simplest solution would be to make all fields Box
variants. But clearly, in this example, indirection is only required on one of the fields. With a more complex type structure however, it's not necessarily so clear (to me at least) where indirection should be added.
Is there an algorithm to calculate where one should insert indirection, given an arbitrary graph of related types, with reasonable efficiency?
As an aside, the actual data that the generated code works with is expressed as literal JSON without references. So I think that we can assume that schemas will never include a non-terminating cycle (i.e. there will always be an Option<T>
somewhere along the way). This should mean that boxing is sufficient, rather than e.g. arena-backed references.
I suppose this isn't strictly a Rust-specific question, but it's at least more relevant to languages which use stack-based values by default.