哈尔滨工业大学编译原理实验报告
实验题目:
词法分析器
学
专
学
姓
院:
业:
号:
名:
计算机科学与技术
信息安全
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;
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 序列