Dart Analyzer: Find instances of a class or its descendants

956 views Asked by At

I am using the build package to take a .dart file and look for definitions of a certain class or its subclasses. Can ClassElement be used for subclasses too?

I am only expecting a single definition of a specific class to be within one file of the project, but there's no reason clients couldn't subclass and go wild.

1

There are 1 answers

2
Nate Bosch On

There is not a way to directly grab all subclasses, but you can find all classes and check if each one is a subclass of the one you're interested in.

Start by getting the LibraryElement for the file you're generating code for with BuildStep.inputLibrary. From there find all the classes in the library with var classes = libraryElement.units.expand((cu) => cu.types);. Then check if each one is a subclass of the class you are interested in by checking whether the ClassElement for the type you are interested in is in ClassElement.allSupertypes for the type you are checking. var subtypes = classes.where((c) => c.allSupertypes.contains(lookingFor));.

You may find the LibraryReader and TypeChecker utilities from source_gen useful.