資源描述:
《編譯原理實驗三 語義分析》由會員上傳分享,免費在線閱讀,更多相關內容在教育資源-天天文庫。
1、編譯原理實驗三語法分析并進行語義分析輸入:經過詞法分析后形成的token[]和tokenstring[]輸出:檢查有無語法錯誤,形成語法樹,并檢查是否符合語義。樣例程序已經能對變量聲明填符號表、進行類型檢查。文法:stmt_seq-->statement;stmt_seq
2、statementstatement-->decl_stmt
3、assign_stmtdecl_stmt-->typevar_listtype-->int
4、floatvar_list-->id,var_list
5、idassign_stmt-->id:=expexp-->exp+term
6、exp-
7、term
8、termterm-->term*factor
9、term*factor
10、factorfactor-->id
11、num
12、(exp)要求掌握理解程序設計方法。樣例程序#include#includetypedefenum{MINUS,PLUS,TIMES,OVER,LPAREN,RPAREN,SEMI,ASSIGN,NUM,ID,INT,FLOAT,COMMA,DOLLAR}tokentype;/*記號*/typedefenum{stmtk,expk}nodekind;typedefenum{ifk,assignk,decl
13、k}stmtkind;typedefenum{opk,constk,idk}expkind;typedefenum{integer,real}exptype;typedefstructtreenode{structtreenode*child[3];structtreenode*sibling;nodekindnodek;exptypedtype;union{stmtkindstmt;expkindexp;}kind;union{tokentypeop;intval;char*name;}attr;}treenode;typedefstructbucket{ch
14、ar*name;exptypedtype;structbucket*next;}bucket;bucket*hashtable[211];/*tokentypetoken[6]={ID,ASSIGN,NUM,PLUS,NUM,INT,FLOAT,COMMA,DOLLAR};chartokenstring[6][30]={"ab",":=","12","+","5","$"};*/tokentypetoken[]={INT,ID,COMMA,ID,SEMI,ID,ASSIGN,NUM,PLUS,NUM,TIMES,NUM,SEMI,ID,ASSIGN,NUM,DO
15、LLAR};chartokenstring[][30]={"int","ab",",","xy",";","ab",":=","12","+","5","*","3",";","xy",":=","34","$"};intwordindex=0;/*以上兩個數組的索引*/treenode*decl();treenode*factor();treenode*term();treenode*exp();treenode*assign_stmt();treenode*stmt_seq();pretraverse(treenode*);inthash(char*);vo
16、idst_insert(char*,exptype);intst_lookup(char*);voidbuildsymtab(treenode*);voidsetnodetype(treenode*);main(){treenode*t;t=stmt_seq();/*語法分析建語法樹*/buildsymtab(t);/*建符號表*/pretraverse(t);/*遍歷語法樹*/setnodetype(t);/*類型檢查設置*/}treenode*stmt_seq(){treenode*t;treenode*p;if((token[wordindex]==INT
17、)
18、
19、(token[wordindex]==FLOAT)){t=decl();}if(token[wordindex]==ID)t=assign_stmt();p=t;while((token[wordindex]==SEMI)&&(token[wordindex]!=DOLLAR)){treenode*q;wordindex++;q=assign_stmt();p->sibling=q;p=q;}returnt;}treenode*assign_stmt(){treenode*t=(treenode*)malloc(sizeof(treenode));if(t
20、oken[wordind