我正在使用source_gen通过Dart analyzer解析一些Dart文件。

我正在扩展GeneratorForAnnotation<>和覆盖方法FutureOr<String> generateForAnnotatedElement(Element element, ConstantReader annotation, BuildStep buildStep)
此方法为我提供了一个基本元素,我可以对其进行导航,直到找到其他元素,例如MethodElement

一旦掌握了这个MethodElement,我想分析一下
该方法的块的详细信息。我想要这样的东西:

AstNode node = methodElement.computeNode();

更详细地:
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();
    }
}

不幸的是,不推荐使用computeNode。如果我尝试调用它,则会得到:
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

我的问题:如何获取AstNode

最佳答案

知道了:

AstNode getAstNodeFromElement(Element element) {
  AnalysisSession session = element.session;
  ParsedLibraryResult parsedLibResult = session.getParsedLibraryByElement(element.library);
  ElementDeclarationResult elDeclarationResult = parsedLibResult.getElementDeclaration(element);
  return elDeclarationResult.node;
}

09-26 22:55