source_gen
source_gen copied to clipboard
Question: how to deal with type hierarchy
Imagine this scenario. I have a class _BaseClass and _SubClass. I want to autogenerate subclasses for both so that I the end I'd have this hierarchy:
_BaseClass
BaseClass // auto generated
_SubClass
SubClass // autogenerated
I'd declare my typed classes as:
class _BaseClass
and
class _SubClass: BaseClass
That almost works except for the fact that I can't get supertype of _SubClass at build time. I assume that happens because build_runner (or source_gen) at the start of generation first deletes autogenerated files (BaseClass and SubClass in my case) and then the declaration
class _SubClass: BaseClass
isn't valid anymore since there is no BaseClass. In fact analyzer returns me an Object as _SubClass' supertype, not BaseClass.
On possible workaround would be to use a custom attribute, i.e.
@hierarchy(superclass: 'BaseClass')
class _SubClass: BaseClass
But this solution is a bit more error prone. Are there any better solutions?
Is it the same builder creating both BaseClass
and SubClass
? If they are different builders then as long as the one for SubClass
runs after the one for BaseClass
it should be able to resolve it.
If they are the same builder then I think it should work to separate your package into two targets, the source file for _SubClass
should be in a target that depends on the one with _BaseClass
. That would enforce that generating SubClass
happens after BaseClass
exists and should be resolvable.
@natebosch It's the same builder. Separating sources in packages is not an option. Imagine a scenario where I have a type hierarchy and I'd like to add augmentation to all of them. Subclass methods should include arguments based on fields on superclass. If I went with different packages, it'd be soon a package mess. Thanks for ideas though, appreciated.