Analyzer
- Dart course
- Expert
- Lesson 28/47
- 5 min
Learn the dart analyzer and plugins.
Analyzer
The analyzer package parses Dart source code into a syntax tree (AST). It is the foundation of code generation and lint checks.
parseString(content: ...) returns a ParseStringResult; the .unit field gives the CompilationUnit (AST root). To traverse nodes, the visitor pattern is used.
RecursiveAstVisitor<T> walks every node; you override methods like visitClassDeclaration, visitMethodDeclaration. This is the standard way to analyze code programmatically.
The visitor pattern
The visitor pattern lets you walk AST nodes by type. Each node type triggers a separate visit... method.
Example: to collect class names, you override visitClassDeclaration. For each class declaration you add the name to a list.
This pattern is common in code analysis and generation. Many tools, including source_gen and custom_lint, use the analyzer's visitor API.
Practice Define a class name collector
Define an ElementInfo class with final String name; ElementInfo(this.name);. Define a ClassCollector class with final List<ElementInfo> classes = []; field and void add(String name) => classes.add(ElementInfo(name)); method. In main create final collector = ClassCollector();; call collector.add('User') and collector.add('Book'); print collector.classes.length; then print names with for (final e in collector.classes) { print(e.name); }.
Starter code
void main() {
// define the ElementInfo class (name field)
// define the ClassCollector class (element list and add method)
// create a collector; add two class names; print count and names
}Sample solution
class ElementInfo {
final String name;
ElementInfo(this.name);
}
class ClassCollector {
final List<ElementInfo> classes = [];
void add(String name) => classes.add(ElementInfo(name));
}
void main() {
final collector = ClassCollector();
collector.add('User');
collector.add('Book');
print(collector.classes.length);
for (final e in collector.classes) {
print(e.name);
}
}Expected output
2 User Book
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does the analyzer produce?
- An AST (syntax tree) Correct answer
- A compiled binary
- A minified bundle
- A test report
Explanation: the analyzer parses source into an AST.
2 Match the analyzer parts
| Term | Meaning |
|---|---|
parseString() |
Source parsing |
CompilationUnit |
AST root |
RecursiveAstVisitor |
Visitor base |
LibraryElement |
Library element |
3 Visitor inheritance
class MyVisitor extends Recursive____Visitor<void> { }
class MyVisitor extends RecursiveAstVisitor<void> { }
Explanation: RecursiveAstVisitor walks all AST nodes.