Reputation: 1
I want to craft a code generator that analyzes the following code:
void main() {
@GenerateCode()
final myClass = MyClass();
myClass.method1('test', ...);
}
My objective is to extract each construction of MyClass
and all the method1
calls with its parameters on that specific construction.
I succeed with finding the main function, but can't succeed in finding the variable myClass
or the construction of MyClass
respectively. I assumed that the .children
on the FunctionElement
for main
would provide me with, among others, the final myClass = MyClass();
line of some sort, but the list is always empty.
Therefor I have two problems:
MyClass
inside the main function?MyClass
was found, how can I list all the method1
calls in the code base, that reference this instance of MyClass
since there could be multiple constructions of MyClass
?This is my debug-approach using a ResursiveElementVisitor. While I can find the main function, no children are accessible.
import 'dart:async';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/visitor.dart';
import 'package:build/build.dart';
import 'package:source_gen/source_gen.dart';
Builder copyBuilder(BuilderOptions options) =>
SharedPartBuilder([MyBuilder()], 'my_builder');
class MyVisitor extends RecursiveElementVisitor {
@override
visitFunctionElement(FunctionElement element) {
print(element.children); // this is an empty list
super.visitFunctionElement(element);
}
}
class MyBuilder implements Generator {
@override
FutureOr<String?> generate(
LibraryReader libraryReader, BuildStep buildStep) async {
libraryReader.element.visitChildren(MyVisitor());
return '';
}
}
Upvotes: 0
Views: 49