新聞中心
你在計(jì)算機(jī)相關(guān)操作中是否遇到過語法分析所獲得的中間結(jié)果例如CST,你想知道CST的實(shí)際相關(guān)應(yīng)用嗎?下面的文章是針對(duì) Python CST 的實(shí)際相關(guān)應(yīng)用與相關(guān)代碼的詳細(xì)介紹,忘你會(huì)從中得到自己想要的東西。

專注于為中小企業(yè)提供成都做網(wǎng)站、網(wǎng)站制作服務(wù),電腦端+手機(jī)端+微信端的三站合一,更高效的管理,為中小企業(yè)錦州免費(fèi)做網(wǎng)站提供優(yōu)質(zhì)的服務(wù)。我們立足成都,凝聚了一批互聯(lián)網(wǎng)行業(yè)人才,有力地推動(dòng)了上1000+企業(yè)的穩(wěn)健成長(zhǎng),幫助中小企業(yè)通過網(wǎng)站建設(shè)實(shí)現(xiàn)規(guī)模擴(kuò)充和轉(zhuǎn)變。
Python CST 和AST 類似,都是語法分析所獲得的中間結(jié)果。他們的不同之處在于,CST直接對(duì)應(yīng)語法分析的匹配的過程,是直接生成的,含有大量冗余信息。而AST省略了中間的冗余信息,直接對(duì)應(yīng)實(shí)際的語義,也就是分析的結(jié)果。用例子說明要清楚一些:
假設(shè)有這樣一個(gè)表達(dá)式a,
Python CST是這樣的:(->表示從父結(jié)點(diǎn)到子結(jié)點(diǎn))
- file_input -> stmt -> simple_stmt -> small_stmt ->
expr_stmt -> testlist -> test ->or_test ->and_test
->not_test -> comparison -> expr -> xor_expr ->
and_expr -> shift_expr -> arith_expr -> term ->- factor -> power -> atom -> (NAME, “a”)
而AST則是:
- (stmt_ty, expr_kind) -> (expr_ty, name_kind) ->(“a”)
可以看到CST表述了整個(gè)分析a的過程,從file_input一直推導(dǎo)到***的NAME,每一步推導(dǎo)都成了樹的結(jié)點(diǎn),而大部分信息都可以說是無用的。AST的結(jié)構(gòu)要簡(jiǎn)單和直接的多,直接表明a是一個(gè)表達(dá)式語句(假定a是一個(gè)單獨(dú)的語句),內(nèi)容是一個(gè)標(biāo)示符,值為”a”。Python的語法分析生成的是 Python CST而非AST,之后Python會(huì)調(diào)用PyAst_FromNode將CST轉(zhuǎn)換為AST。
CST的結(jié)點(diǎn)稱為Node,其結(jié)構(gòu)定義在node.h中:
- typedef struct _node {
- short n_type;
- char *n_str;
- int n_lineno;
- int n_col_offset;
- int n_nchildren;
- struct _node *n_child;
- } node;
- Field
- Description
- n_type
結(jié)點(diǎn)類型,終結(jié)符定義在token.h中,而非終結(jié)符定義在graminit.h中
n_str
結(jié)點(diǎn)所對(duì)應(yīng)的字符串的內(nèi)容
n_lineno
對(duì)應(yīng)的行號(hào)
n_col_offset
列號(hào)
n_nchildren
子結(jié)點(diǎn)的個(gè)數(shù)
n_child
子結(jié)點(diǎn)數(shù)組,動(dòng)態(tài)分配內(nèi)存
Python提供了下面的函數(shù)/宏來操作CST,同樣定義在node.h中:
- PyAPI_FUNC(node *) PyNode_New(int type);
- PyAPI_FUNC(int) PyNode_AddChild(node *n, int type,
- char *str, int lineno, int col_offset);
- PyAPI_FUNC(void) PyNode_Free(node *n);
- /* Node access functions */
- #define NCH(n) ((n)->n_nchildren)
- #define CHILD(n, i) (&(n)->n_child[i])
- #define RCHILD(n, i) (CHILD(n, NCH(n) + i))
- #define TYPE(n) ((n)->n_type)
- #define STR(n) ((n)->n_str)
- /* Assert that the type of a node is what we expect */
- #define REQ(n, type) assert(TYPE(n) == (type))
- PyAPI_FUNC(void) PyNode_ListTree(node *);
以上就是對(duì) Python CST 和AST 類似,都是語法分析所獲得的中間結(jié)果。他們的不同之處在于,CST直接對(duì)應(yīng)語法分析的匹配的過程,是直接生成的,含有大量冗余信息。而AST省略了中間的冗余信息,直接對(duì)應(yīng)實(shí)際的語義,也就是分析的結(jié)果。用例子說明相關(guān)的內(nèi)容的介紹,忘你會(huì)有所收獲。
文章題目:PythonCST和AST類似之處的詳細(xì)介介紹
當(dāng)前路徑:http://m.5511xx.com/article/dpdgdpj.html


咨詢
建站咨詢
