Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the AstNode from some Element, in Dart Analyzer / source-gen?

I'm using source_gen to parse some Dart files, through the Dart analyzer.

I'm extending GeneratorForAnnotation<>, and overriding method FutureOr<String> generateForAnnotatedElement(Element element, ConstantReader annotation, BuildStep buildStep). This method gives me a base element, which I navigate until I find some other element, say a MethodElement.

Once I get hold of this MethodElement, I want to analyze the method's block, in detail. I'd like something like this:

AstNode node = methodElement.computeNode();

In more detail:

class MyGenerator extends GeneratorForAnnotation<MyAnnotation> {

    @override
    FutureOr<String> generateForAnnotatedElement(
        Element element, ConstantReader annotation, BuildStep buildStep,
    ) {
      if (element is ClassElement)
        for (MethodElement methodElement in element.methods) {
          AstNode node = methodElement.computeNode();
          processMyNode(node);
        }
      else
        throw AssertionError();
    }
}

Unfortunately, computeNode is deprecated. If I try to call it, I get:

NoSuchMethodError: Class 'RestrictedAnalysisContext' has no instance method 'resolveCompilationUnit' with matching arguments.
Receiver: Instance of 'RestrictedAnalysisContext'
Tried calling: resolveCompilationUnit(Instance of 'FileSource', Instance of 'LibraryElementImpl')
Found: resolveCompilationUnit(Source, LibraryElement) => CompilationUnit

My question: How can I get the AstNode?

like image 783
MarcG Avatar asked Jul 14 '19 20:07

MarcG


1 Answers

Got it:

AstNode getAstNodeFromElement(Element element) {
  AnalysisSession session = element.session;
  ParsedLibraryResult parsedLibResult = session.getParsedLibraryByElement(element.library);
  ElementDeclarationResult elDeclarationResult = parsedLibResult.getElementDeclaration(element);
  return elDeclarationResult.node;
}
like image 51
MarcG Avatar answered Sep 21 '22 15:09

MarcG