作者:手机用户2502857335 | 来源:互联网 | 2023-07-21 17:24
AST(抽象语法树)是Flutter对Dart文件分词(类似)的一种结果,它可以把程序员编写的Dart语句逐个分解为json格式,如下最基本的一个Helloworld页面被转换后的结果
AST(抽象语法树)是Flutter对Dart文件分词(类似)的一种结果,它可以把程序员编写的Dart语句逐个分解为json格式,如下最基本的一个 Hello world 页面被转换后的结果:
通过调用analyzer parseString/parseFile方法可以对Dart代码字符串分析成Json类型的AST,官方并没有把AST中各个字段所表达的意义一一说明,这给做Fflutter动态能力的增加了不少障碍,这里将对照源码一一分析它的意义。
Dart源代码:
class DemoWidget extends StatefulWidget {
@override
_DemoWidgetState createState() => _DemoWidgetState();
}
class _DemoWidgetState extends State {
@override
Widget build(BuildContext context) {
return Text('Hello world!');
}
}
如上所示是一个简单的StatefulWidget Hello world!页面,转换成AST后如下所示:
[
{
"type": "ClassDeclaration",
"id": {
"type": "Identifier",
"name": "DemoWidget"
},
"superClause": {
"type": "TypeName",
"name": "StatefulWidget"
},
"implementsClause": null,
"mixinClause": null,
"metadata": [],
"body": [
{
"type": "MethodDeclaration",
"id": {
"type": "Identifier",
"name": "createState"
},
"parameters": {
"type": "FormalParameterList",
"parameterList": []
},
"typeParameters": null,
"body": null,
"isAsync": false,
"returnType": {
"type": "TypeName",
"name": "_DemoWidgetState"
}
}
]
},
{
"type": "ClassDeclaration",
"id": {
"type": "Identifier",
"name": "_DemoWidgetState"
},
"superClause": {
"type": "TypeName",
"name": "State"
},
"implementsClause": null,
"mixinClause": null,
"metadata": [],
"body": [
{
"type": "MethodDeclaration",
"id": {
"type": "Identifier",
"name": "build"
},
"parameters": {
"type": "FormalParameterList",
"parameterList": [
{
"type": "SimpleFormalParameter",
"paramType": {
"type": "TypeName",
"name": "BuildContext"
},
"name": "context"
}
]
},
"typeParameters": null,
"body": {
"type": "BlockStatement",
"body": [
{
"type": "ReturnStatement",
"argument": {
"type": "MethodInvocation",
"callee": {
"type": "Identifier",
"name": "Text"
},
"typeArguments": null,
"argumentList": {
"type": "ArgumentList",
"argumentList": [
{
"type": "StringLiteral",
"value": "Hello world!"
}
]
}
}
}
]
},
"isAsync": false,
"returnType": {
"type": "TypeName",
"name": "Widget"
}
}
]
}
]
analyzer只支持顶级类转换,不支持顶级变量、方法或mixin等类型。
AST关键属性讲解:
类Class
{
"type": "ClassDeclaration",
"id": {
"type": "Identifier",
"name": "DemoWidget"
},
"superClause": {
"type": "TypeName",
"name": "StatefulWidget"
},
"implementsClause": null,
"mixinClause": null,
"metadata": [],
"body": [
]
}