在Python_ast.h中AST所用到的类型定义,我们以stmt_ty类型的相关代码为例来介绍Python_ast.h中AST所用到的类型,希望大姐在浏览完以下的文章会在Python_ast.h中AST的相关实际应用中有所收获。
AST所用到的类型均定义在Python_ast.h中,以stmt_ty类型为例:
enum _stmt_kind {FunctionDef_kind=1, ClassDef_kind=2, Return_kind=3,
Delete_kind=4, Assign_kind=5, AugAssign_kind=6, Print_kind=7,
For_kind=8, While_kind=9, If_kind=10, With_kind=11,
Raise_kind=12, TryExcept_kind=13, TryFinally_kind=14,
Assert_kind=15, Import_kind=16, ImportFrom_kind=17,
Exec_kind=18, Global_kind=19, Expr_kind=20, Pass_kind=21,
Break_kind=22, Continue_kind=23};
struct _stmt {
enum _stmt_kind kind;
union {
struct {
identifier name;
arguments_ty args;
asdl_seq *body;
asdl_seq *decorators;
} FunctionDef;
struct {
identifier name;
asdl_seq *bases;
asdl_seq *body;
} ClassDef;
struct {
expr_ty value;
} Return;
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
过长,中间从略
struct {
expr_ty value;
} Expr;
} v;
int lineno;
int col_offset;
};
typedef struct _stmt *stmt_ty;
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
stmt_ty是语句结点类型,实际上是_stmt结构的指针。_stmt结构比较长,但有着很清晰的Pattern:
1. 第一个Field为kind,代表语句的类型。_stmt_kind定义了_stmt的所有可能的语句类型,从函数定义语句,类定义语句直到Continue语句共有23种类型。
2. 接下来是一个union v,每个成员均为一个struct,分别对应_stmt_kind中的一种类型,如_stmt.v.FunctionDef对应了_stmt_kind枚举中的FunctionDef_Kind,也就是说,当_stmt.kind == FunctionDef_Kind时,_stmt.v.FunctionDef中保存的就是对应的函数定义语句的具体内容。#t#
3. 其他数据,如lineno和col_offset
大部分AST结点类型均是按照类似的pattern来定义的,不再赘述。除此之外,另外有一种比较简单的AST类型如operator_ty,expr_context_ty等,由于这些类型仍以_ty结尾,因此也可以认为是AST的结点,但实际上,这些类型只是简单的枚举类型,并非指针。因此在以后的文章中,并不把此类AST类型作为结点看待,而是作为简单的枚举处理
以上就是对AST所用到的类型均定义在Python_ast.h中,以stmt_ty类型为例相关的内容的介绍,以及其具有清晰的Pattern的具体体现,忘你会有所收获。