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
?
Got it:
AstNode getAstNodeFromElement(Element element) {
AnalysisSession session = element.session;
ParsedLibraryResult parsedLibResult = session.getParsedLibraryByElement(element.library);
ElementDeclarationResult elDeclarationResult = parsedLibResult.getElementDeclaration(element);
return elDeclarationResult.node;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With