有没有办法在 PreOrder、postOrder 或 inOrder 中遍历由 dart Analyzer 组成的 AST。我正在使用访问节点使用 GeneralizingAstVisitor 遍历 AST 树,但它只是从代码的顶部到底部递归地遍历它。
import'package:analyzer/src/generated/testing/element_factory.dart';
import 'package:analyzer/analyzer.dart';
import 'dart:io';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/file_system/physical_file_system.dart';
import 'package:analyzer/src/context/builder.dart';
import 'package:analyzer/src/dart/sdk/sdk.dart';
import 'package:analyzer/src/generated/engine.dart';
import 'package:analyzer/src/generated/sdk.dart' show DartSdk;
import 'package:analyzer/src/generated/source.dart';
import 'package:analyzer/src/generated/source_io.dart';
import 'package:analyzer/src/source/source_resource.dart';
main() {
LibraryElement libElement;
Source source;
AnalysisContext context;
var ast = parseCompilationUnit(src,
parseFunctionBodies: true, suppressErrors: true);
print(ast.toSource());
PhysicalResourceProvider resourceProvider = PhysicalResourceProvider.INSTANCE;
DartSdk sdk = new FolderBasedDartSdk(resourceProvider,
resourceProvider.getFolder("/usr/local/opt/dart/libexec"));
var resolvers = [
new DartUriResolver(sdk),
];
context = AnalysisEngine.instance.createAnalysisContext()
..sourceFactory = new SourceFactory(resolvers);
source = new FileSource(resourceProvider.getFile(
"/Users/shubhamkumar/Sites/projects/flutterX/dart_analyser/demo.dart"));
ChangeSet changeSet = new ChangeSet()..addedSource(source);
context.applyChanges(changeSet);
libElement = context.computeLibraryElement(source);
callAST(context, source, libElement);
}
class Visitor1 extends GeneralizingAstVisitor {
@override
visitNode(AstNode node) {
print("node $node ${node.runtimeType} ");
node.childEntities.forEach((n) => print(n));
return super.visitNode(node);
}
}
callAST(context, source, libElement) {
CompilationUnit resolvedUnit =
context.resolveCompilationUnit(source, libElement);
var visitor = new Visitor1();
resolvedUnit.accept(visitor);
}
如果您有任何解决方案,请提供帮助。