资源描述:
《编译原理实验三 语义分析》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
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