source_gen icon indicating copy to clipboard operation
source_gen copied to clipboard

Question: how to deal with type hierarchy

Open MihaMarkic opened this issue 5 years ago • 2 comments

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?

MihaMarkic avatar May 14 '19 07:05 MihaMarkic

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 avatar May 23 '19 19:05 natebosch

@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.

MihaMarkic avatar May 24 '19 06:05 MihaMarkic