如何使用 Dart 分析器类构建反映 AST 的树实例?

问题描述 投票:0回答:1

我想使用

analyzer
包来解析
build
函数中定义的小部件树,并自动将每个方法调用的代码分解为单独的方法。

假设下面的示例输入包含需要分解的大量小部件树,最好基于

child
children
属性。在示例中,我想导航到
MyApp
类声明、
build
方法声明、
return MaterialApp...
return 语句,然后导航到该函数中的每个命名表达式,例如
theme
 home

但是,我不确定如何约束

AstVisitor
,让我能够沿着特定路径跟踪 AST,而不仅仅是访问该类型树中的所有节点。
AstVisitor
文档也不能保证它遍历树的顺序,这意味着我可以以确定性的方式重建小部件树。

我的做法是错的吗?

输入示例:

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
          useMaterial3: true,
        ),
        home: Scaffold(
          appBar: AppBar(title: const Text('Foo Bar Baz')),
          body: null,
        ));
  }
}

我的代码:

class _BuildMethodVisitor extends RecursiveAstVisitor<UINode> {
  final UINode root;

  _BuildMethodVisitor(this.root) : super();

  @override
  UINode? visitClassDeclaration(ClassDeclaration node) {
    print('classDeclaration::${node.name}');

    super.visitClassDeclaration(node);

    return null;
  }

  @override
  UINode? visitReturnStatement(ReturnStatement node) {
    print('returnStatement::${node}');

    super.visitReturnStatement(node);

    return null;
  }

  @override
  UINode? visitNamedExpression(NamedExpression node) {
    print('namedExpression::${node}');

    super.visitNamedExpression(node);

    return null;
  }

  @override
  UINode? visitMethodInvocation(MethodInvocation node) {
    print('methodInvocation::${node}');

    super.visitMethodInvocation(node);

    return null;
  }
}
dart abstract-syntax-tree analyzer decomposition
1个回答
0
投票

最简单的接口可能是带有代码修复的 custom_lint。 Remi 投入了大量精力来简化 lint 和重构,并为设计不佳的事情提供变通办法。您可以在您的追求中检查一下。

© www.soinside.com 2019 - 2024. All rights reserved.