Python_ast.h相關(guān)代碼的詳細(xì)介紹
在Python_ast.h中AST所用到的類型定義,我們以stmt_ty類型的相關(guān)代碼為例來介紹Python_ast.h中AST所用到的類型,希望大姐在瀏覽完以下的文章會在Python_ast.h中AST的相關(guān)實(shí)際應(yīng)用中有所收獲。
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;
過長,中間從略
- struct {
- expr_ty value;
- } Expr;
- } v;
- int lineno;
- int col_offset;
- };
- typedef struct _stmt *stmt_ty;
stmt_ty是語句結(jié)點(diǎn)類型,實(shí)際上是_stmt結(jié)構(gòu)的指針。_stmt結(jié)構(gòu)比較長,但有著很清晰的Pattern:
1. 第一個Field為kind,代表語句的類型。_stmt_kind定義了_stmt的所有可能的語句類型,從函數(shù)定義語句,類定義語句直到Continue語句共有23種類型。
2. 接下來是一個union v,每個成員均為一個struct,分別對應(yīng)_stmt_kind中的一種類型,如_stmt.v.FunctionDef對應(yīng)了_stmt_kind枚舉中的FunctionDef_Kind,也就是說,當(dāng)_stmt.kind == FunctionDef_Kind時,_stmt.v.FunctionDef中保存的就是對應(yīng)的函數(shù)定義語句的具體內(nèi)容。#t#
3. 其他數(shù)據(jù),如lineno和col_offset
大部分AST結(jié)點(diǎn)類型均是按照類似的pattern來定義的,不再贅述。除此之外,另外有一種比較簡單的AST類型如operator_ty,expr_context_ty等,由于這些類型仍以_ty結(jié)尾,因此也可以認(rèn)為是AST的結(jié)點(diǎn),但實(shí)際上,這些類型只是簡單的枚舉類型,并非指針。因此在以后的文章中,并不把此類AST類型作為結(jié)點(diǎn)看待,而是作為簡單的枚舉處理
以上就是對AST所用到的類型均定義在Python_ast.h中,以stmt_ty類型為例相關(guān)的內(nèi)容的介紹,以及其具有清晰的Pattern的具體體現(xiàn),忘你會有所收獲。