Workiva / dart_codemod

A library that makes it easy to write and run automated code modifications on a codebase.
Other
61 stars 11 forks source link

Finding unused classes #36

Open lukepighetti opened 3 years ago

lukepighetti commented 3 years ago

I'm just poking around with dart_codemod and I was wondering if someone would be willing to suggest/discuss a strategy for finding unused classes.

My idea was to visit every class declaration and get the name of the class, then search the rest of the AST for any use of the constructor. I tried to walk the tree and wasn't successful.

void main(List<String> arguments) {
  runInteractiveCodemod(
    filePathsFromGlob(Glob('**.dart', recursive: true)),
    PrintEveryCommentInProject(),
    args: arguments,
  );
}

class PrintEveryCommentInProject extends GeneralizingAstVisitor
    with AstVisitingSuggestorMixin {
  @override
  dynamic visitDeclaration(Declaration node) {
    print(node.documentationComment);

    node.visitChildren(this);
  }
}
evanweible-wf commented 3 years ago

Hi @lukepighetti! I think you'd need a fully resolved AST (or maybe an ElementVisitor) so that you can determine where each class is located in addition to its name, otherwise you could have classes that are distinct but named the same.

Either way, I'd probably start by writing a visitor that implements visitClassDeclaration to collect all of the classes, and then pass that info to another visitor that implements visitTypeName to determine which classes are unused. I haven't tested that idea, so there might be another visit method that would be better.. I can never quite keep all the analyzer APIs straight in my head :)

Couple other things to keep in mind:

Hopefully that helps!