logo资料库

哈尔滨工业大学编译原理实验报告.doc

第1页 / 共9页
第2页 / 共9页
第3页 / 共9页
第4页 / 共9页
第5页 / 共9页
第6页 / 共9页
第7页 / 共9页
第8页 / 共9页
资料共9页,剩余部分请下载后查看
哈尔滨工业大学编译原理实验报告 实验题目: 词法分析器 学 专 学 姓 院: 业: 号: 名: 计算机科学与技术 信息安全 1050320113 孙琦
1. 实验目的: 通过本实验加深对词法分析程序的功能及实现方法的理 解 2. 实验内容: 编写一个词法分析程序,对给出的程序段进行词法分析, 要求输出以文件形式存放的 TOKEN 串和符号表 3. 实验设计: 1 文法描述 标识符描述: id  letter ( letter | dight)* letter  A | B | … | X | Y | Z | a | b | … | x | y | z dight  0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 实形数描述: num  dights optional_fraction dights  dight dight* optional_fraction  .dights | ε dight  0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 2 用于实验分析的程序例子 #include /*测试程序*/ void main() { int num1; float num2,num3; for(int i=0;i<10;i++) cout<10) { num1=12; num2=23.67;
num3=num1+num2; cout< ( ) = ; << 编码 1 2 3 4 5 6 7 8 9 单词 ++ + { } , include void main int 编码 10 11 12 13 14 15 16 17 18 单词 for cout if cout Int ID / Float float 编码 19 20 21 22 23 24 25 26 27 4 程序中用到的数据结构 //TOKEN 字的数据结构 typedef struct{ int type; int index; char name[NAMEMAX]; //单词的机内码 //符号表中的入口地址 //符号名称 }list; typedef struct{ char name[NAMEMAX]; int type; }key_word; 5 词法分析程序中主要模块的算法 //关键字名称 //关键字的机内码 主调度函数的算法: void main() { init(); scan(); //读入符号表 //浏览 } void scan() { 读入文件并进行判断是否出错; ch=fgetc(fp_read); while(ch!=EOF) { //读入
clean(l.name); if(((ch>64)&&(ch<90))||((ch>96)&&(ch<123)))//判断标识符 ID_check(); else { if(ch=='/') Notice_check(); //判断注释 else { } else if(((ch>47)&&(ch<58))) Num_check(); //判断数字 others(); //其他情况 } } void ID_check() { int i=0,tag=0; while(读入是字母或数字或下滑线) { 写入 l.name[i]=ch; i++; ch=fgetc(fp_read); } for(i=0;i
char ch_next; ch=fgetc(fp_read); if(ch='*') { while(1) { //判断是否是注释/* ch=fgetc(fp_read); if(ch=='*') { ch_next=fgetc(fp_read); if(ch_next=='/') { ch=fgetc(fp_read); return; } } } } else if(ch='/') { 是否为// ch=fgetc(fp_read); while(ch!='/t') ch=fgetc(fp_read); ch=fgetc(fp_read); return; } else { l.index=-1; l.name[0]='/'; l.type=25; Print(); } } void Num_check() { int i=0; l.type=23; while(((ch>47)&&(ch<58))) { l.name[i]=ch; i++; ch=fgetc(fp_read); if(ch=='.') //数字判断
{ } l.name[i]='.'; l.type=26; i++; ch=fgetc(fp_read); while(((ch>47)&&(ch<58))) { l.name[i]=ch; i++; ch=fgetc(fp_read); } } l.index=token_index++; Print(); } void others() { char tem; if(ch== '<') { //其他情况 //<<和++特殊,分开,其他用查找 match() tem=ch; ch=fgetc(fp_read); if(ch=='<') { l.type=9; l.name[0]=l.name[1]='<'; l.index=-1; Print(); ch=fgetc(fp_read); return; } else { l.type=2; l.name[0]='<'; l.index=-1; Print(); return; } } else if(ch== '+') { tem=ch;
} else { } l.type=11; l.name[0]='+'; l.index=-1; Print(); return; } else if(ch==10||ch==13) { line_index++; ch=fgetc(fp_read); return; } else if(ch==' '||ch==9) { ch=fgetc(fp_read); return; ch=fgetc(fp_read); if(ch=='+') { l.type=10; l.name[0]=l.name[1]='+'; l.index=-1; Print(); ch=fgetc(fp_read); return; } else { } int flag=match(ch); if(flag==-1) cout<<"error"; else { l.index=-1; l.name[0]=key[flag].name[0]; l.type=key[flag].type; Print(); } ch=fgetc(fp_read);
} 6 词法分析后的生成的 TOKEN 文件和符号表 TOKEN 序列
分享到:
收藏