我正在使用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
?
答案 0 :(得分:0)
知道了
AstNode getAstNodeFromElement(Element element) {
AnalysisSession session = element.session;
ParsedLibraryResult parsedLibResult = session.getParsedLibraryByElement(element.library);
ElementDeclarationResult elDeclarationResult = parsedLibResult.getElementDeclaration(element);
return elDeclarationResult.node;
}