编译原理实验二 语法分析
输入:token[40]
tokenstring[40][30]
输出:检查是否符合文法];
生成语法树。
样例程序已经对符合以下文法的源程序进行语法分析但不能生成抽象语法树。
要求写出能生成抽象语法树的语法分析程序。
文法: stmt_q stmt_q ; assign_stmt | assign_stmt
assign_stmt id := exp
expexp + term | exp – term | term
termterm * factor | term / factor | factor
factor ( exp ) | id | num
语法树的数据结构:
typedef enum {stmtk,expk} nodekind;
typedef enum {ifk,assignk,declk} stmtkind;
typedef enum {opk,constk,idk} expkind;
采风报告
typedef struct treenode
清明时节雨 { struct treenode * child[3];
struct treenode * sibling;
nodekind nodek;
union { stmtkind stmt; expkind exp;} kind;
union { tokentype op;
int val;
潍坊小吃 char * name; } attr;
} treenode;
样例程序
王开头的成语#include<stdio.h>
抽烟对肝有影响吗#include<ctype.h>
typedef enum {PLUS,MINUS,TIMES,OVER,LPAREN,RPAREN,SEMI,ASSIGN,NUM,ID,DOLLAR} tokentype;/*记号*/
tokentype token[]={ID,ASSIGN,NUM,PLUS,NUM,TIMES,NUM,SEMI,ID,ASSIGN,NUM,DOLLAR}; /*存记号*/
char tokenstring[][30]={"ab",":=","12","+","5","*","3",";","xy",":=","34","$"};/*存记号串*/
int wordindex=0; /*以上两个数组的索引*/
factor();
term();
exp();
assign_stmt();
stmt_q();
main()
{ stmt_q();
}
stmt_q()
{assign_stmt();
while( (token[wordindex]==SEMI)&& (token[wordindex]!=DOLLAR))
{wordindex++;
assign_stmt();
}
}
assign_stmt()
{if(token[wordindex]==ID)
父母对幼儿园孩子的简短寄语 wordindex++;
el {printf("error");
exit(1);}
if(token[wordindex]==ASSIGN)
wordindex++;
el {printf("error");
exit(1);}
exp();
}
exp()
{term();
while((token[wordindex]==PLUS)||(token[wordindex]==MINUS))
{wordindex++;
term();}
}
term()
{factor();
while((token[wordindex]==TIMES)||(token[wordindex]==OVER))
{wordindex++;升旗仪式主持词
factor();}
}优秀范文
factor()
{switch(token[wordindex]){
ca LPAREN :
wordindex++;
exp();
if(token[wordindex]==RPAREN)
wordindex++;
el {printf("error");
exit(1);}
break;
ca NUM :
wordindex++;
break;
ca ID :
wordindex++;
break;
default:
printf("error");
}
}